Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #define MAX 1000
- using namespace std;
- nhapMang(int n, int a[])
- {
- for(int i = 1; i <= n; i++)
- {
- cout << "Nhap phan tu thu a[" << i << "]: ";
- cin >> a[i];
- }
- }
- xuatMang(int n, int a[])
- {
- for(int i = 1; i <= n; i++)
- {
- cout << "Phan tu thu a[" << i << "] la: " << a[i] << endl;
- }
- }
- void Upheap(int a[], int position)
- {
- int value = a[position];
- while (position / 2 > 0)
- {
- int parent = position / 2;
- if (a[parent] <= value)
- {
- break;
- }
- a[position] = a[parent];
- position = parent;
- }
- a[position] = value;
- }
- void Downheap(int a[], int heapSize, int position)
- {
- int value = a[position];
- while (position * 2 <= heapSize)
- {
- int child = position * 2;
- if (child < heapSize && a[child+1] < a[child])
- {
- ++child;
- }
- if (value <= a[child])
- {
- break;
- }
- a[position] = a[child];
- position = child;
- }
- a[position] = value;
- }
- int main()
- {
- int n, a[MAX], heap[MAX];
- cout << "Nhap so luong phan tu: ";
- cin >> n;
- cout << "\n\n\t\tNHAP MANG" << endl;
- nhapMang(n, a);
- cout << "\n\n\t\tMANG DA SAP XEP\n";
- int heapSize;
- for (int i=1; i<=n; ++i)
- {
- Upheap(a, i);
- }
- heapSize = n;
- for (int i=n; i>=1; --i)
- {
- swap(a[1], a[i]);
- heapSize--;
- Downheap(a, heapSize, 1);
- }
- xuatMang(n, a);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement