实现 思路 先将序列的第1个记录看成是一个有序的子序列,然后从第2个记录逐个进行插入,直至整个序列有序为止。 实现 升序排列代码 void insert_sort(int a[], int n){ // n不合法或只有1个元素就不会排序了 if ( n < 2) { return; } // 遍历待插入元素 for(int i = 1; i < n; ++i){ if (a[i] < a[i-1]){ int j = i - 1; // 有序序列结尾元素下标 int val = a[i]; // 待插入元素值 // 元素依次后挪,给val腾位置 while((j >= 0) && (a[j] > val)){ a[j + 1] = a[j]; --j; } a[j + 1] = val; } // 测试用 print(a, n, i); } } 测试 代码 #include <iostream> using namespace std; void print (int a[], int num, int index) { cout << index << " : "; for (int i= 0; i < num; ++i) { cout << a[i] << " "; } cout << endl; } int main() { int a[] = {7,6,5,4,3,2,1}; insert_sort(a, sizeof(a)/sizeof(a[0])); cin.get(); return 0; } 结果 1 : 6 7 5 4 3 2 1 2 : 5 6 7 4 3 2 1 3 : 4 5 6 7 3 2 1 4 : 3 4 5 6 7 2 1 5 : 2 3 4 5 6 7 1 6 : 1 2 3 4 5 6 7