插入排序的原理同很多人打牌时,整理手中的牌时的做法差不多。在开始摸牌时,左手是空的,接着一次从桌上摸起一张牌,并将它插入到左手一把牌中的正确位置上,这样左手的牌永远都是顺序摆放的。
插入排序伪代码如下:
INSERT-SORT(A) for j <-- 2 to length[A] do key <-- A[j] > Insert A[j] into the sorted sequence A[1..j-1]. i <-- j - 1 while i > 0 and A[i] > key do A[i+1] <-- A[i] i <-- i - 1 A[i+1] <-- key
根据伪代码很容易写出c代码:
void insert_sort(int a[], int len) { int i, j; int key; for (j = 1; j < len; j++) { key = a[j]; i = j - 1; while (i >= 0 && a[i] > key) { a[i+1] = a[i]; i--; } a[i+1] = key; } }
完整代码如下:
#include <stdio.h> void dump(int a[], int len) { int i; for (i = 0; i < len; i++) { printf("%3d", a[i]); } printf(" "); } void insert_sort(int a[], int len) { int i, j; int key; for (j = 1; j < len; j++) { key = a[j]; i = j - 1; while (i >= 0 && a[i] > key) { a[i+1] = a[i]; i--; } a[i+1] = key; } } int main(void) { int a[] = {3, 1, 0, 4, 6, 2, 9, 8, 7, 5}; int len = sizeof(a) / sizeof(a[0]); dump(a, len); insert_sort(a, len); dump(a, len); return 0; }
程序运行结果为:
3 1 0 4 6 2 9 8 7 5
0 1 2 3 4 5 6 7 8 9