1.插入排序, 从第二个数开始,先将第二个数做一个副本放在一旁(变量中)。
2.第二个数同前一个数比较,小于则用前一个数覆盖第二个数, 然后将副本放在前一个数前面5.重复4步骤,直到最后一个数:
#include <stdio.h> /*插入法排序*/ void sort3(int *digits, int nums) { int i = 0, j = 0, k = 0; int tmp_digit = 0; for(i = 1; i < nums; i++) { tmp_digit = digits[i]; for(j = i - 1; j >= 0; j--) { if(digits[j] > tmp_digit) { digits[j + 1] = digits[j]; } else { break; } } if(j != i - 1) { digits[j + 1] = tmp_digit; } for(k = 0; k < nums; k++) { printf("%d ", digits[k]); } printf("\n"); } } int main(void) { int nums = 0; int digits[] = {9,8,7,6,10,5,11,4,3,2,1,0}; int i = 0; nums = sizeof(digits) / sizeof(nums); sort3(digits, nums); for(i = 0; i < nums; i++) { printf("%d ", digits[i]); } printf("\n"); return 0; }
1: 8 9 7 6 10 5 11 4 3 2 1 0
2: 7 8 9 6 10 5 11 4 3 2 1 0
3: 6 7 8 9 10 5 11 4 3 2 1 0
4: 6 7 8 9 10 5 11 4 3 2 1 0
5: 5 6 7 8 9 10 11 4 3 2 1 0
6: 5 6 7 8 9 10 11 4 3 2 1 0
7: 4 5 6 7 8 9 10 11 3 2 1 0
8: 3 4 5 6 7 8 9 10 11 2 1 0
9: 2 3 4 5 6 7 8 9 10 11 1 0
10: 1 2 3 4 5 6 7 8 9 10 11 0
11: 0 1 2 3 4 5 6 7 8 9 10 11
改进方法:二分法插入法排序
#include <stdio.h> int find_digit_idx(int *digits, int compare_digit, int start_index, int end_index) { int i = 0; while(start_index <= end_index) { i = (start_index + end_index) / 2; if(compare_digit < digits[i]) { end_index = i - 1; } else { start_index = i + 1; } } /*start_index的时候就是刚好可以插入的地方*/ return start_index; } /*插入法排序*/ void sort3(int *digits, int nums) { int i = 0, j = 0, start_index = 0; int tmp_digit = 0; for(i = 1; i < nums; i++) { tmp_digit = digits[i]; start_index = find_digit_idx(digits, tmp_digit, 0, i - 1); for(j = i - 1; j >= start_index; j--) { digits[j + 1] = digits[j]; } if(j != i - 1) { digits[j + 1] = tmp_digit; } } } int main(void) { int nums = 0; int digits[] = {9,8,7,6,10,5,11,4,3,2,1,0}; int i = 0; nums = sizeof(digits) / sizeof(nums); sort3(digits, nums); for(i = 0; i < nums; i++) { printf("%d ", digits[i]); } printf("\n"); return 0; }