插入排序(Insert sort)
插入排序的伪代码:
For j=2 to A.length Key =A[j] //插入A[j] i=j-1 while i>0 and A[i]>key A[i+1]=A[i]; i=i-1; A[i+1]=key
执行情况:
5 2 4 6 1 3
2 5 4 6 1 3
2 4 5 6 1 3
2 4 5 6 6 3
2 4 5 5 6 3
2 4 4 5 6 3
2 2 4 5 6 3
1 2 4 5 6 3
....
C语言代码:
1 #include<stdio.h> 2 void Insert_sort(int *p_A); 3 int main() 4 { 5 int i; 6 int A[6] = { 5, 2, 4, 6, 1, 3 }; 7 Insert_sort(A); 8 for (i = 0; i < 6; i++) 9 printf("%d\t", A[i]); 10 printf("\nhello.."); 11 system("pause"); 12 return 0; 13 } 14 void Insert_sort(int *p_A) 15 { 16 int key, i, j; 17 for (j = 1; j < 6; j++) 18 { 19 key = p_A[j]; 20 i = j - 1; 21 while (i >= 0 && p_A[i] > key) 22 { 23 p_A[i + 1] = p_A[i]; 24 i = i - 1; 25 } 26 p_A[i + 1] = key; 27 } 28 }
插入排序算法的时间复杂度为 O(n2)。

浙公网安备 33010602011771号