void insertion_sort(int a[], int len) { int i, j, x; for (j = 1; j < len; j++) { x = a[j]; i = j - 1; while (i >= 0 && x < a[i]) { a[i+1] = a[i--]; } a[++i] = x; } }
测试用例
#include <stdio.h> int main() { int a[] = {5, 1, 7, 12, 9, 6}; int i; insertion_sort(a, 6); for (i = 0; i < 6; i++) { printf("%d%s", a[i], (i==5)?"\n":" "); } return 0; }