- 1.
- 2. /*
- 3. * 算法思想:跟玩扑克牌时自己整理牌的思想是一样的.
- 4. * 首先,只有一张牌,可看做是已有序了.
- 5. * 然后,每进来一张牌(第N张牌),就需要在前面已有序的(N-1)张
- 6. * 牌进行扫描,找到自己应该插入的位置. 然后插入.
- 7. */
- 8.
- 9. //input: array name and the length of the array.
- 10. //output: void.
- 11. void insert_sort(int array[], int n)
- 12. {
- 13. int i; //i is the index of going to be sorted number.
- 14. int j; //j is the index of sorted numbers.
- 15. int key; //the key number which is going to be sorted.
- 16. //外循环从1开始.array[0]默认是已有序了.只需要把后面的n-1个数进行排序即可
- 1. for (i=1; i<n; i++)
- 2. {
- 3. key = array[i];
- 4. j=i-1;
- 5. //顺序扫描前面已有序的数组,查找到需要插入的正确位置.
- 6. while (j>=0 && key<array[j])
- 7. {
- 8. array[j+1] = array[j];
- 9. j--;
- 10. }//while
- 11.
- 12. //insert the array[i] into the correct position.
- 13. array[j+1] = key;
- 14.
- 15. }//for
- 16. }//insert-sort()