Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. #include <ctime>
  4.  
  5. void swap(int& a, int& b)
  6. {
  7. int temp = a;
  8. a = b;
  9. b = temp;
  10. }
  11.  
  12. //1->n 0->n - 1
  13. //2i, 2i + 1 2i + 1, 2i + 2
  14. //n / 2 n / 2 - 1
  15. //while(l>0) while(l>=0)
  16.  
  17. void shift(int *a, int l, int r)
  18. {
  19. int i = l, j = 2 * i + 1, x = a[i];
  20. while (j <= r)
  21. {
  22. if (j < r)
  23. if (a[j] > a[j + 1])j++;
  24. if (x <= a[j])break;
  25.  
  26. a[i] = a[j];
  27. i = j;
  28. j = 2 * i + 1;
  29. }
  30. a[i] = x;
  31. }
  32.  
  33. void initHeap(int *a, int n)
  34. {
  35. int l = n/ 2 - 1;
  36. while (l>=0)
  37. {
  38. shift(a, l, n - 1);
  39. l--;
  40. }
  41. }
  42.  
  43. void heapSort(int *a, int n)
  44. {
  45. initHeap(a, n);
  46. int r = n - 1;
  47. while (r > 0)
  48. {
  49. swap(a[0], a[r]);
  50. r--;
  51. shift(a, 0, r);
  52. }
  53. }
  54.  
  55. void khoiTaoMang(int *&a, int &n)
  56. {
  57. srand(time(NULL));
  58. n = 20;
  59. a = new int[n];
  60.  
  61. for (int i = 0; i < n; i++)
  62. {
  63. a[i] = -10 + rand() % (10 + 10 + 1);
  64. }
  65. }
  66.  
  67. void xuatMang(int *a, int n)
  68. {
  69. for (int i = 0; i < n; i++)
  70. {
  71. cout << a[i] << " ";
  72. }
  73. }
  74.  
  75. int main()
  76. {
  77. int *a;
  78. int n;
  79.  
  80. khoiTaoMang(a, n);
  81. xuatMang(a, n);
  82.  
  83. cout << endl << endl;
  84.  
  85. heapSort(a, n);
  86. xuatMang(a, n);
  87.  
  88. delete[] a;
  89. system("pause");
  90. return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement