堆排序算法C++实现
#include <iostream>
#include <vector>
using namespace std;
void maxHeap(std::vector<int>& in, int i, int size);
void heapBuild(std::vector<int>& vec);
void heapSort(std::vector<int>& in);
void swap(std::vector<int>& in, int index1, int index2);
void swap(std::vector<int>& in, int index1, int index2) {
int tmp = in[index1];
in[index1] = in[index2];
in[index2] = tmp;
}
void maxHeap(std::vector<int>& in, int i, int size) {
int root = i;
int left = i * 2;
int right = i * 2 + 1;
int max = root;
if (left <= size && in[left - 1] > in[max - 1]) {
max = left;
}
if (right <= size && in[right - 1] > in[max - 1]) {
max = right;
}
if (left <= size && max == left) {
swap(in, root - 1, left - 1);
maxHeap(in, left, size);
} else if (right <= size && max == right) {
swap(in, root - 1, right - 1);
maxHeap(in, right, size);
}
}
void heapBuild(std::vector<int>& vec) {
for (int i = vec.size() / 2; i > 0; --i) {
maxHeap(vec, i, vec.size());
}
}
void heapSort(std::vector<int>& in) {
heapBuild(in);
for (int size = in.size(); size > 1; --size) {
swap(in, 0, size-1);
maxHeap(in, 1, size-1);
}
}
int main() {
std::vector<int> input = {1,25, 24, 34, 65, 1, 214, -89, 74};
heapSort(input);
for (auto it : input) {
cout << it << " ";
}
cout << endl;
return 0;
}