堆排序:
通过堆的特点,先将头结点(即最大值的节点)与最后一个节点交换,堆大小-1,那么最大值就在最后,之后的操作也不会干扰到他,在把交换上去的节点,进行调整,使堆恢复正常,重复操作。
#include<iostream>
#include<Windows.h>
#define MAX_LENGTH 100
using namespace std;
typedef struct Heap {
int* arr;
int size;
int max_length;
}Heap;
bool init(Heap& heap, int* arry, int size);
bool popMAX(Heap& heap, int& value);
void Build_Heap(Heap& heap);
void adjustDown(Heap& heap, int index);
void Heap_sort(Heap& heap);
int main() {
Heap heap;
int arry[] = { 1, 2, 3, 87, 93, 82, 92, 86, 95 };
//堆的初始化
if (!init(heap, arry, sizeof(arry) / sizeof(arry[0]))) {
cout << "初始化失败" << endl;
}
for (int i = 0; i < heap.size; i++) {
printf("the %dth element:%d\n", i, heap.arr[i]);
}
Heap_sort(heap);
for (int i = 0; i < heap.max_length; i++) {
printf("%d\n",heap.arr[i]);
}
system("pause");
return 0;
}
bool init(Heap& heap, int* arry, int size) {
heap.size = heap.max_length = size;
heap.arr = arry;
Build_Heap(heap);
return true;
}
void Build_Heap(Heap& heap) {
for (int i = (heap.size / 2) - 1;i >= 0;i--) {
adjustDown(heap, i);
}
}
void adjustDown(Heap& heap, int index) {
int tmp = heap.arr[index];
int child, parent;
for (parent = index;parent * 2 + 1 < heap.size;parent = child) {
child = parent * 2 + 1;
if ((child + 1) < heap.size && heap.arr[child] < heap.arr[child + 1]) {
child++;
}
if (tmp < heap.arr[child]) {
heap.arr[parent] = heap.arr[child];
heap.arr[child] = tmp;
}
else {
break;
}
}
}
bool popMAX(Heap& heap, int& value) {
if (heap.size == 0) {
cout << "堆为空" << endl;
return false;
}
value = heap.arr[0];
heap.arr[0] = heap.arr[--heap.size];
adjustDown(heap, 0);
return true;
}
void Heap_sort(Heap& heap) {
while (heap.size) {
int tmp = heap.arr[0];
heap.arr[0] = heap.arr[heap.size - 1];
heap.arr[heap.size - 1] = tmp;
heap.size--;
adjustDown(heap, 0);
}
}