Advertisement
Guest User

sắp síp heapsort

a guest
Dec 7th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #define MAX 1000
  4. using namespace std;
  5.  
  6. nhapMang(int n, int a[])
  7. {
  8.     for(int i = 1; i <= n; i++)
  9.     {
  10.         cout << "Nhap phan tu thu a[" << i << "]: ";
  11.         cin >> a[i];
  12.     }
  13. }
  14.  
  15. xuatMang(int n, int a[])
  16. {
  17.     for(int i = 1; i <= n; i++)
  18.     {
  19.         cout << "Phan tu thu a[" << i << "] la: " << a[i] << endl;
  20.     }
  21. }
  22.  
  23. void Upheap(int a[], int position)
  24. {
  25.     int value = a[position];
  26.     while (position / 2 > 0)
  27.     {
  28.         int parent = position / 2;
  29.         if (a[parent] <= value)
  30.         {
  31.         break;
  32.         }
  33.         a[position] = a[parent];
  34.         position = parent;
  35.     }
  36.     a[position] = value;
  37. }
  38.  
  39. void Downheap(int a[], int heapSize, int position)
  40. {
  41.     int value = a[position];
  42.     while (position * 2 <= heapSize)
  43.     {
  44.         int child = position * 2;
  45.         if (child < heapSize && a[child+1] < a[child])
  46.         {
  47.         ++child;
  48.         }
  49.         if (value <= a[child])
  50.         {
  51.         break;
  52.         }
  53.         a[position] = a[child];
  54.         position = child;
  55.     }
  56.     a[position] = value;
  57. }
  58.  
  59. int main()
  60. {
  61.     int n, a[MAX], heap[MAX];
  62.     cout << "Nhap so luong phan tu: ";
  63.     cin >> n;
  64.     cout << "\n\n\t\tNHAP MANG" << endl;
  65.     nhapMang(n, a);
  66.    
  67.     cout << "\n\n\t\tMANG DA SAP XEP\n";
  68.     int heapSize;
  69.     for (int i=1; i<=n; ++i)
  70.     {
  71.         Upheap(a, i);
  72.     }
  73.     heapSize = n;
  74.     for (int i=n; i>=1; --i)
  75.     {
  76.         swap(a[1], a[i]);
  77.         heapSize--;
  78.         Downheap(a, heapSize, 1);
  79.     }
  80.     xuatMang(n, a);
  81.    
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement