Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- void heapify(int array[], const int, int);
- void printarray(int array[], const int);
- void heapsort(int array[], const int);
- int main() {
- const int size = 6;
- int array[size] = { 77, 15, 91, 21, 6, 46 }; //given values but to be sorted using minimum
- cout << "\nGiven: ";
- printarray(array, size);
- for (int h = size / 2; h >= 0; h--) {
- heapify(array, size, h);
- }
- cout << "\nHeapified: ";
- printarray(array, size);
- heapsort(array, size);
- cout << "\nSorted: ";
- printarray(array, size); //seems like it prints the sorted array backwards when uaing the smallest as the pivot or something
- return 0;
- }
- void heapify(int array[], const int size, int h) {
- int smallest = h; //declare smallest
- int low = (2 * h) + 1;
- int high = (2 * h) + 2;
- if (low < size && array[low] < array[smallest]) { //if left child is smaller than the root
- smallest = low;
- }
- if (high < size && array[high] < array[smallest]) { //if right child is smaller than "smallest", also it seems like <else if> statement doesn't work here, only <if if>
- smallest = high;
- }
- if (smallest != h) { //if smallest is not root
- swap(array[h], array[smallest]);
- heapify(array, size, smallest);
- }
- }
- void printarray(int array[], const int size) {
- for (int h = 0; h < size; h++) {
- cout << array[h] << ' ';
- }
- }
- void heapsort(int array[], const int size) {
- for (int h = size / 2; h >= 0; h--) {
- heapify(array, size, h);
- }
- for (int h = size -1; h >= 0; h--) {
- swap(array[0], array[h]);
- heapify(array, h, 0);
- }
- }
- /*
- Heapified tree:
- 6
- / \
- 15 46
- /\ /
- 21 71 91
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement