插入排序
C++代码:
template <typename T> void SortUtil<T>::insertionSort(vector<T>& data) { int j = 0; for (int i = 1; i < data.size(); i++) { T key = data[i]; // insert data[i] into the sorted sequence data[0..i-1] j = i; while (j > 0 && data[j - 1] > key) { data[j] = data[j - 1]; j--; } data[j] = key; } }
测试代码(C++):
void display(vector<int> data) { for (auto& elem : data) { cout << elem << endl; } } int main(int argc, char* argv[]) { vector<int> data1 { 9, 5, 18, 21, 32, 93, 2 }; cout << "before sort:" << endl; display(data1); SortUtil<int>::insertionSort(data1); cout << "after sort:" << endl; display(data1); }
运行结果:
before sort:
9
5
18
21
32
93
2
after sort:
2
5
9
18
21
32
93