fork download
  1. #include <stdio.h>
  2.  
  3. #define N 20
  4.  
  5. int main()
  6. {
  7. int a[N] = {
  8. 45, 12, 78, 3, 56,
  9. 29, 91, 17, 64, 8,
  10. 33, 70, 1, 52, 86,
  11. 24, 39, 95, 11, 60
  12. };
  13.  
  14. int i, j, temp;
  15.  
  16. printf("排序前的数据:\n");
  17. for(i = 0; i < N; i++)
  18. printf("%d ", a[i]);
  19.  
  20. // 直接插入排序
  21. for(i = 1; i < N; i++)
  22. {
  23. temp = a[i];
  24. j = i - 1;
  25.  
  26. while(j >= 0 && a[j] > temp)
  27. {
  28. a[j + 1] = a[j];
  29. j--;
  30. }
  31.  
  32. a[j + 1] = temp;
  33. }
  34.  
  35. printf("\n\n直接插入排序后的数据:\n");
  36. for(i = 0; i < N; i++)
  37. printf("%d ", a[i]);
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0s 5340KB
stdin
Standard input is empty
stdout
排序前的数据:
45 12 78 3 56 29 91 17 64 8 33 70 1 52 86 24 39 95 11 60 

直接插入排序后的数据:
1 3 8 11 12 17 24 29 33 39 45 52 56 60 64 70 78 86 91 95