Last active
September 13, 2019 06:04
-
-
Save say4n/23143581e230f0d724a5ea452916fe48 to your computer and use it in GitHub Desktop.
heap, heap-sort implementation in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<vector> | |
#include<math.h> | |
using namespace std; | |
void display(vector<int> arr, std::FILE* stream=stdout) { | |
for(auto it=arr.begin(); it!=arr.end(); it++) { | |
fprintf(stream, "%d ", *it); | |
} | |
fprintf(stream, "\n"); | |
} | |
void heapify(vector<int> &arr, int start, int end) { | |
int offset = start; | |
for(int i=end-start; i>=0; i--) { | |
int key = arr[i+offset]; | |
if (2*i + offset < arr.size()) { | |
// left child exists | |
fprintf(stderr, "i: %d, p: %d, l: %d\n", i, key, arr[2*i + offset]); | |
if (key > arr[2*i + offset]) { | |
fprintf(stderr, "left child, swap\n"); | |
arr[i + offset] = arr[2*i + offset]; | |
arr[2*i + offset] = key; | |
key = arr[i]; | |
} | |
} | |
if (2*i + 1 + offset< arr.size()) { | |
// right child exists | |
fprintf(stderr, "i: %d, p: %d, r: %d\n", i, key, arr[2*i + 1]); | |
if (key > arr[2*i + 1 + offset]) { | |
fprintf(stderr, "i: %d, right child, swap\n", i); | |
arr[i + offset] = arr[2*i + 1 + offset]; | |
arr[2*i + 1 + offset] = key; | |
key = arr[i + offset]; | |
} | |
} | |
} | |
} | |
void heapsort(vector<int> &arr) { | |
for(int start=0; start<arr.size(); start++) { | |
fprintf(stderr, "heapify:s=%d, e=%d\n", start, int(arr.size()/2 + 1)); | |
heapify(arr, start, arr.size()); | |
} | |
} | |
int main() { | |
vector<int> arr = {33,2,27,5,7,13,9,6,11,1}; | |
// display(arr); | |
// heapify(arr, 0, floor(arr.size()/2)); | |
heapsort(arr); | |
display(arr); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.PHONY: all | |
all: heap | |
heap: heap.cpp | |
$(CXX) -std=c++11 heap.cpp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment