用堆实现数组的排序 (从小到大)
//代码:
#include
#include <Windows.h>
using namespace std;
#define MAX_SIZE 10
//堆排序
typedef struct _Heap {
int *arr; //首地址
int size; //元素个数
int capacity; //元素容量
}_Heap;
//整理堆
static void adjustDown(_Heap *p_heap,int index) {
if (!p_heap) {
return;
}
int tmp = p_heap->arr[index];
int parent, child;
for (parent = index; parent * 2 + 1 < p_heap->size; parent = child) {
child = parent * 2 + 1;
if (child + 1 < p_heap->size && p_heap->arr[child + 1] > p_heap->arr[child]) {
child = child + 1;
}
//子节点的最大的节点的值大于父节点的值
if (p_heap->arr[child] > tmp) {
p_heap->arr[parent] = p_heap->arr[child];
p_heap->arr[child] = tmp;
}
else {
break;
}
}
}
//建堆
static void buildHeap(_Heap *p_heap) {
if (!p_heap) {
return;
}
for (int i = (p_heap->size - 1 - 1) / 2; i >= 0; i--) {
adjustDown(p_heap, i);
}
}
//进行最大值排序
bool popMax(_Heap *p_heap) {
if (!p_heap) {
return false;
}
while (p_heap->size > 0) {
int tmp = p_heap->arr[0];
p_heap->arr[0] = p_heap->arr[p_heap->size - 1];
p_heap->arr[p_heap->size - 1] = tmp;
p_heap->size--;
//首节点
adjustDown(p_heap, 0);
}
return true;
}
//初始化
bool heapInit(_Heap *p_heap, int *p_data) {
if (!p_heap || !p_data) {
return false;
}
p_heap->arr = p_data;
if (!p_heap) {
return false;
}
//容量
p_heap->capacity = MAX_SIZE;
p_heap->size = MAX_SIZE;
//建堆
buildHeap(p_heap);
return true;
}
int main(void) {
_Heap heap;
int data[MAX_SIZE] = { 18,20,45,13,52,19,53,44,37,22 };
if (!(heapInit(&heap, data))) {
fprintf(stderr, "建堆失败!\n");
exit(-1);
}
//排序
if (!(popMax(&heap))) {
fprintf(stderr, "进行堆排序失败!\n");
exit(-1);
}
for (int i = 0; i < MAX_SIZE; i++) {
cout << data[i] << ' ';
}
system("pause");
return 0;
}