堆排序是基本排序算法中常见的一类排序方法。它利用堆这一数据结构的性质来进行排序的。排序主要分为两步,首先将一个数组转换成堆数组。我们将这个堆数组分成两段,一段是有序队列,一段是余下的数组。有序队列始终位于堆数组的末尾。最开始有序队列长度为0。由于堆数组的根节点是整个堆的最大(最小)元素。这样我们将堆数组的末尾元素与根节点交换。此时有序队列增加了第一个元素,它是整个堆数组里面的最大(小)元素。对余下的数组,通过调整,使之恢复成为堆数组,再将余下数组的末端与根节点元素交换,依次类推,最终有序队列包含了这个待排序数组的所有元素,我们也完成了排序。
具体实现如下:
#include<iostream>
#include<time.h>
//每一轮保证自start节点之后的节点都满足堆的性质
void makeHeap(int array[], int start, int end) {
int dad = start;
int child = 2 * dad + 1;
while (child <= end) {
if (child + 1 <= end && array[child + 1] > array[child])
child = child + 1;
if (array[child] < array[dad])
return;
else {
int temp = array[child];
array[child] = array[dad];
array[dad] = temp;
dad = child;
child = 2 * dad + 1;
}
}
}
void heapSort(int array[],int n) {
//将数组转换为最大堆
//对每个非叶子节点进行调整。
for (int i = n / 2 - 1;i >= 0;i--) {
makeHeap(array, i, n - 1);
}
//将根节点按顺序依次挪到堆的末端
for (int i = n - 1;i >= 1;i--) {
int temp = array[0];
array[0] = array[i];
array[i] = temp;
makeHeap(array, 0, i-1);
}
}
void getNewArray(int array[], int n) {
for (int i = 0;i < n;i++) {
array[i] = rand() % 100;
}
}
void test(int array[], int n) {
bool v = false;
for (int i = 0;i < n - 1;i++) {
if (array[i] > array[i + 1]) {
v = true;
cout << "Error sort " <<i<< endl;
break;
}
}
}
int main() {
const int NUM = 100000;
BucketsSort *h = new BucketsSort();
srand((unsigned)time(NULL));
int *array=new int[NUM];
cout << "start..." << endl;
clock_t now = clock();
getNewArray(array, NUM);
now = clock();
heapSort(array, NUM);
cout << "heap sort swap is :" << clock() - now << endl;
test(array, NUM);
delete array;
//print(NUM, array);
delete h;
return 0;
}