Skip to content

Instantly share code, notes, and snippets.

@sillykelvin
Created December 23, 2014 12:36
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 sillykelvin/081dce3ed0d95d31b6ad to your computer and use it in GitHub Desktop.
Save sillykelvin/081dce3ed0d95d31b6ad to your computer and use it in GitHub Desktop.
C++ heap sort
#include <algorithm>
#include <iostream>
using namespace std;
#define ARR_LEN(arr) (sizeof(arr) / sizeof(arr[0]))
struct element {
int id;
int score;
};
struct comp {
bool operator()(const element& left, const element& right) const {
return left.score < right.score;
}
};
int main() {
element arr[] = {{1, 1}, {2, 10}, {3, 2}, {4, 5}, {5, 7}, {6, 8}, {7, 6}, {8, 4}, {9, 9}, {10, 3}};
for (int i = 0; i < ARR_LEN(arr); ++i) {
cout << "id: " << arr[i].id << ", score: " << arr[i].score << " | ";
}
cout << endl;
comp c;
make_heap(arr, arr + ARR_LEN(arr), c);
for (int i = 0; i < ARR_LEN(arr); ++i) {
cout << "id: " << arr[i].id << ", score: " << arr[i].score << " | ";
}
cout << endl;
sort_heap(arr, arr + ARR_LEN(arr), c);
for (int i = 0; i < ARR_LEN(arr); ++i) {
cout << "id: " << arr[i].id << ", score: " << arr[i].score << " | ";
}
cout << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment