Merge pull request #700 from ericcurtin/dont-start-at-index-1

heapsort implementation started at index 1
This commit is contained in:
Bhaumik Mistry 2020-01-08 10:27:15 -05:00 committed by GitHub
commit eb1284cd15
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,54 +1,52 @@
#include <algorithm>
#include <iostream> #include <iostream>
void max_heapify(int *a, int i, int n) { void heapify(int *a, int i, int n) {
int j, temp; int largest = i;
temp = a[i]; const int l = 2 * i + 1;
j = 2 * i; const int r = 2 * i + 2;
while (j <= n) {
if (j < n && a[j + 1] > a[j]) if (l < n && a[l] > a[largest])
j = j + 1; largest = l;
if (temp > a[j]) {
break; if (r < n && a[r] > a[largest])
} else if (temp <= a[j]) { largest = r;
a[j / 2] = a[j];
j = 2 * j; if (largest != i) {
} std::swap(a[i], a[largest]);
heapify(a, n, largest);
} }
a[j / 2] = temp;
return;
} }
void heapsort(int *a, int n) { void heapsort(int *a, int n) {
int i, temp; for (int i = n - 1; i >= 0; --i) {
for (i = n; i >= 2; i--) { std::swap(a[0], a[i]);
temp = a[i]; heapify(a, 0, i);
a[i] = a[1];
a[1] = temp;
max_heapify(a, 1, i - 1);
} }
} }
void build_maxheap(int *a, int n) { void build_maxheap(int *a, int n) {
int i; for (int i = n / 2 - 1; i >= 0; --i) {
for (i = n / 2; i >= 1; i--) { heapify(a, i, n);
max_heapify(a, i, n);
} }
} }
int main() { int main() {
int n, i; int n;
std::cout << "Enter number of elements of array\n"; std::cout << "Enter number of elements of array\n";
std::cin >> n; std::cin >> n;
int a[20]; int a[20];
for (i = 1; i <= n; i++) { for (int i = 0; i < n; ++i) {
std::cout << "Enter Element " << (i) << std::endl; std::cout << "Enter Element " << i << std::endl;
std::cin >> a[i]; std::cin >> a[i];
} }
build_maxheap(a, n); build_maxheap(a, n);
heapsort(a, n); heapsort(a, n);
std::cout << "Sorted Output\n"; std::cout << "Sorted Output\n";
for (i = 1; i <= n; i++) { for (int i = 0; i < n; ++i) {
std::cout << a[i] << std::endl; std::cout << a[i] << std::endl;
} }
std::getchar(); std::getchar();
} }