插入排序的思想:就像打牌一样,每摸一张牌,就把这张牌插入到手上已经排好序的牌中。
程序:
#include <iostream>
using namespace std;
void InsertSort(int a[], int length) {
for (int i = 0; i < length; i++) {
for (int j = i; j > 0; j--) {
if (a[j - 1] > a[j]) {
int temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
else {
break;
}
}
}
}
int main() {
int a[10] = { 10, 13, 8, 6, 12, 15, 2, 20, 18, 28 };
int length = 10;
//BubbleSort(a, length);
//QuickSort(a, 0, length - 1);
InsertSort(a, length);
//SelectSort(a, length);
//HeapSort(a, length);
//MergeSort(a, length);
for (int i = 0; i < 10; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
输出结果:
复杂度分析:未完待续