#include<iostream>
#include<vector>
using namespace std;
void AdustDown(vector<int> &arr,int curr,int len) {
int child;
while(curr * 2 + 1 <= len) {
child = curr * 2 + 1;
if (child + 1 <= len) {
if (arr[child] < arr[child + 1]) {
child++;
}
}
if (arr[curr] < arr[child]) {
swap(arr[curr],arr[child]);
curr = child;
}
else {
break;
}
}
}
int main() {
vector<int> arr = {5,7,3,2,13,6,2,1,6,9,89,54,234,978,6,454,8789,438,654,4,3213,435,56,456};
for (int i = (arr.size()-1) / 2; i >= 0; i--) {
AdustDown(arr, i,arr.size()-1);
}
for (int i = arr.size() - 1; i >= 0; i--) {
swap(arr[0], arr[i]);
AdustDown(arr, 0, i-1);
}
for (int i = 0; i < arr.size(); i++) {
cout << arr[i] << endl;
}
return 0;
}
堆排序
最新推荐文章于 2024-09-04 23:05:17 发布