main.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //
  2. // Created by tangs on 2018/11/16.
  3. //
  4. #include <iostream>
  5. using namespace std;
  6. // 书上的折半插入排序, 与直接插入排序的区别,就是在查找插入位置时,使用了
  7. // 二分法,除此之外思想也是一样的。
  8. void InsertSort(int A[], int n) {
  9. int i, j, low, high, mid;
  10. for (i = 2; i < n; i++) {
  11. A[0] = A[i];
  12. low = 1;
  13. high = i - 1;
  14. while (low <= high) {
  15. mid = (low + high) / 2;
  16. if (A[mid] > A[0]) {
  17. high = mid - 1;
  18. } else {
  19. low = mid + 1;
  20. }
  21. }
  22. for (j = i - 1; j >= high + 1; --j) {
  23. A[j + 1] = A[j];
  24. }
  25. A[high + 1] = A[0];
  26. }
  27. }
  28. // 自己实现
  29. void InsertSortBySelf(int A[], int n) {
  30. int i, j, low, high, mid = 0, temp;
  31. for (i = 1; i < n; i++) {
  32. if (A[i] > A[i - 1]) {
  33. continue;
  34. }
  35. temp = A[i];
  36. low = 0, high = i - 1;
  37. while (low <= high) {
  38. mid = (low + high) / 2;
  39. if (A[mid] > temp) {
  40. high = mid - 1;
  41. } else {
  42. low = mid + 1;
  43. }
  44. }
  45. for (j = i - 1; j >= mid; --j) {
  46. A[j + 1] = A[j];
  47. }
  48. A[j + 1] = temp;
  49. }
  50. }
  51. int main() {
  52. int A1[] = {6, 1, 5, 2, 1, 9, 10, 24, 7, 0};
  53. InsertSort(A1, 10);
  54. // print:
  55. // 0 0 1 1 2 5 7 9 10 24
  56. for (int i = 0; i < 10; i++) {
  57. cout << A1[i] << " ";
  58. }
  59. cout << endl;
  60. int A2[] = {6, 1, 5, 2, 1, 9, 10, 24, 7, 0};
  61. InsertSortBySelf(A2, 10);
  62. // print:
  63. // 0 0 1 1 2 5 7 9 10 24
  64. for (int i = 0; i < 10; i++) {
  65. cout << A1[i] << " ";
  66. }
  67. cout << endl;
  68. return 0;
  69. }