看到了《算法导论》的insertion sort,又加之现在在学习C++,于是乎把算法实现了一遍,特此记录
insertionSort.cpp
void insertionSort(int * a, int length) {
for (int i = 1; i < length; i++) {
int target = *(a + i);
int j = i - 1;
while (j >= 0 && *(a + j) > target) {
*(a + j + 1) = *(a + j);
j--;
}
*(a + j + 1) = target;
}
}
main.cpp
#include <iostream>
using namespace std;
void insertionSort(int * a, int length);
void printArray(int * a, int length);
int main()
{
int a[] = {5, 3, 1, 5, 7, 9};
printArray(a, 6);
insertionSort(a, 6);
cout << "after" << endl;
printArray(a, 6);
return 0;
}
void printArray(int * a, int length) {
cout << "The array is: ";
for (int i = 0; i < length; i++) {
cout << *(a + i) << " ";
}
cout << endl;
}