main.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // Created by tangs on 2018/11/18.
  3. //
  4. #include <iostream>
  5. using namespace std;
  6. // 抄书的算法;
  7. // 希尔排序的时间复杂度涉及到一个未解决的数学难题,当n在某个范围内时,可以达到O(n^1.3).
  8. // 最坏的时候为O(n^2).
  9. void ShellSort(int A[], int n) {
  10. int dk, i, j;
  11. for (dk = n / 2; dk >= 1; dk /= 2) {
  12. for (i = dk ; i < n; i++) {
  13. if (A[i] < A[i - dk]) {
  14. A[0] = A[i];
  15. for (j = i - dk; j > 0 && A[0] < A[j]; j -= dk) {
  16. A[j + dk] = A[j];
  17. }
  18. A[j + dk] = A[0];
  19. }
  20. }
  21. }
  22. }
  23. void ShellSortBySelf(int A[], int n) {
  24. int dk, i, j;
  25. int temp;
  26. for (dk = n / 2; dk >= 1; dk /= 2) {
  27. for (i = dk; i < n; i++) {
  28. if (A[i] < A[i - dk]) {
  29. temp = A[i];
  30. for (j = i-dk; j >= 0 && A[j]>temp; j -= dk) {
  31. A[j + dk] = A[j];
  32. }
  33. A[j + dk] = temp;
  34. }
  35. }
  36. }
  37. }
  38. int main(){
  39. int A1[] = {6, 1, 5, 2, 1, 9, 10, 24, 7, 0};
  40. ShellSort(A1, 10);
  41. // print:
  42. // 0 0 1 1 2 5 7 9 10 24
  43. for (int i = 0; i < 10; i++) {
  44. cout << A1[i] << " ";
  45. }
  46. cout << endl;
  47. // --------------------------------------------------------------------------
  48. int A2[] = {6, 1, 5, 2, 1, 9, 10, 24, 7, 0};
  49. ShellSortBySelf(A2, 10);
  50. // print:
  51. // 0 1 1 2 5 6 7 9 10 24
  52. for (int i = 0; i < 10; i++) {
  53. cout << A2[i] << " ";
  54. }
  55. cout << endl;
  56. return 0;
  57. }