堆排序:
构建一个完全二叉树,根据要求构建大顶堆或者小顶堆,交换第一个节点个最后一个节点,然后重新构建大顶堆或者小顶堆
#include<iostream>
#include<bits/stdc++.h>
#include<vector>
using namespace std;
void swap(int a[], int i, int j) {
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
//建立大根堆
//void Down(int a[], int i, int n) {
// int parent = i;
// int child = 2 * i + 1;
// while (child < n) {
// if (child + 1 < n && a[child + 1] > a[child]) {
// child++;
// }
// if (a[parent] < a[child]) {
// swap(a, parent, child);
// parent = child;
// }
// child = 2 * child + 1;
// }
//}
//建立小根堆
void Down(int a[], int i, int n) {
int parent = i;
int child = 2 * i + 1;
while (child < n) {
if (child + 1 < n && a[child + 1] < a[child]) {
child++;
}
if (a[parent] > a[child]) {
swap(a, parent, child);
parent = child;
}
child = 2 * child + 1;
}
}
void Heapsort(int a[], int n) {
for (int i = n / 2 - 1; i >= 0; --i) {
Down(a, i, n);
}
for (int i = n - 1; i >= 0; --i) {
swap(a, 0, i);
Down(a, 0, i);
}
}
int main() {
int a[6] = { 2,3,5,0,4,1 };
Heapsort(a,6);
for (int i = 0; i < 6; ++i) {
cout << a[i] << " ";
}
return 0;
}