Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@say4n
Last active September 13, 2019 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save say4n/23143581e230f0d724a5ea452916fe48 to your computer and use it in GitHub Desktop.
Save say4n/23143581e230f0d724a5ea452916fe48 to your computer and use it in GitHub Desktop.
heap, heap-sort implementation in C++
#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;
}
.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