2020-01-06 19:23:29 +08:00
|
|
|
#include <algorithm>
|
2019-12-16 20:21:16 +08:00
|
|
|
#include <iostream>
|
|
|
|
|
2020-01-06 19:23:29 +08:00
|
|
|
void heapify(int *a, int i, int n) {
|
|
|
|
int largest = i;
|
|
|
|
const int l = 2 * i + 1;
|
|
|
|
const int r = 2 * i + 2;
|
|
|
|
|
|
|
|
if (l < n && a[l] > a[largest])
|
|
|
|
largest = l;
|
|
|
|
|
|
|
|
if (r < n && a[r] > a[largest])
|
|
|
|
largest = r;
|
|
|
|
|
|
|
|
if (largest != i) {
|
|
|
|
std::swap(a[i], a[largest]);
|
|
|
|
heapify(a, n, largest);
|
2019-12-16 20:21:16 +08:00
|
|
|
}
|
|
|
|
}
|
2020-01-04 16:33:56 +08:00
|
|
|
|
2019-12-16 20:21:16 +08:00
|
|
|
void heapsort(int *a, int n) {
|
2020-01-06 19:23:29 +08:00
|
|
|
for (int i = n - 1; i >= 0; --i) {
|
|
|
|
std::swap(a[0], a[i]);
|
|
|
|
heapify(a, 0, i);
|
2019-12-16 20:21:16 +08:00
|
|
|
}
|
|
|
|
}
|
2020-01-04 16:33:56 +08:00
|
|
|
|
2019-12-16 20:21:16 +08:00
|
|
|
void build_maxheap(int *a, int n) {
|
2020-01-06 19:23:29 +08:00
|
|
|
for (int i = n / 2 - 1; i >= 0; --i) {
|
|
|
|
heapify(a, i, n);
|
2019-12-16 20:21:16 +08:00
|
|
|
}
|
|
|
|
}
|
2020-01-04 16:33:56 +08:00
|
|
|
|
2019-12-16 20:21:16 +08:00
|
|
|
int main() {
|
2020-01-06 19:23:29 +08:00
|
|
|
int n;
|
2019-12-16 20:21:16 +08:00
|
|
|
std::cout << "Enter number of elements of array\n";
|
|
|
|
std::cin >> n;
|
|
|
|
int a[20];
|
2020-01-06 19:23:29 +08:00
|
|
|
for (int i = 0; i < n; ++i) {
|
|
|
|
std::cout << "Enter Element " << i << std::endl;
|
2019-12-16 20:21:16 +08:00
|
|
|
std::cin >> a[i];
|
|
|
|
}
|
2020-01-06 19:23:29 +08:00
|
|
|
|
2019-12-16 20:21:16 +08:00
|
|
|
build_maxheap(a, n);
|
|
|
|
heapsort(a, n);
|
|
|
|
std::cout << "Sorted Output\n";
|
2020-01-06 19:23:29 +08:00
|
|
|
for (int i = 0; i < n; ++i) {
|
2020-01-04 16:33:56 +08:00
|
|
|
std::cout << a[i] << std::endl;
|
2019-12-16 20:21:16 +08:00
|
|
|
}
|
2020-01-06 19:23:29 +08:00
|
|
|
|
2019-12-16 20:21:16 +08:00
|
|
|
std::getchar();
|
|
|
|
}
|