C++ 数据结构算法 学习笔记(15) - 堆排序
堆排序讲解
堆排序(Heapsort)是指利用堆这种数据结构所设计的一种排序算法,它是选择排序的一种。可以利用数组的特 点快速定位指定索引的元素. (选择排序工作原理 - 第一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置, 然后再从剩余的未排序元素中寻找到最小(大)元素,然后放到已排序的序列的末尾。以此类推,直到全部待 排序的数据元素的个数为零
完整代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DataType;
#define isLess(a,b) (a<b)
typedef struct _PriorityQueue {
DataType* arr;
int size;
int capacity;
}PriorityQueue;
bool init(PriorityQueue& pq, int* orginal, int size);
bool pop(PriorityQueue& pq, DataType& value);
bool isEmpty(PriorityQueue& pq);
bool isFull(PriorityQueue& pq);
void destroy(PriorityQueue& pq);
void heapSort(PriorityQueue& pq);
static void build(PriorityQueue& pq);
static void adjustDown(PriorityQueue& pq, int index);
bool init(PriorityQueue& pq, DataType* orginal, int size) {
//pq.arr = new DataType[capacity];
pq.arr = orginal;
if (!pq.arr) return false;
pq.capacity = size;
pq.size = size;
if (size > 0) {
//memcpy(pq.arr, orginal, size * sizeof(int));
build(pq);
}
return true;
}
void destroy(PriorityQueue& pq) {
if (pq.arr) delete[] pq.arr;
}
bool isEmpty(PriorityQueue& pq) {
if (pq.size < 1) return true;
return false;
}
bool isFull(PriorityQueue& pq) {
if (pq.size < pq.capacity) return false;
return true;
}
int size(PriorityQueue& pq) {
return pq.size;
}
void build(PriorityQueue& pq) {
int i;
for (i = pq.size / 2 - 1; i >= 0; i--) {
adjustDown(pq, i);
}
}
void adjustDown(PriorityQueue& pq, int index)
{
DataType cur = pq.arr[index];
int parent, child;
for (parent = index; (parent * 2 + 1) < pq.size; parent = child) {
child = parent * 2 + 1;
if (((child + 1) < pq.size) && isLess(pq.arr[child], pq.arr[child
+ 1])) {
child++;
}
if (isLess(pq.arr[child], cur)) {
break;
}
else {
pq.arr[parent] = pq.arr[child];
pq.arr[child] = cur;
}
}
}
/* Sorting function*/
void heapSort(PriorityQueue& pq)
{
if (isEmpty(pq)) return;
while (pq.size > 0)
{
int tmp = pq.arr[0];
pq.arr[0] = pq.arr[pq.size - 1];
pq.arr[pq.size - 1] = tmp;
pq.size--;
adjustDown(pq, 0);
}
}
bool pop(PriorityQueue& pq, DataType& value) {
if (isEmpty(pq)) return false;
value = pq.arr[0];
pq.arr[0] = pq.arr[--pq.size];
//heap.arr[0] = heap.arr[heap.size-1];
//heap.size--;
adjustDown(pq, 0);
return true;
}
int main(void) {
PriorityQueue pq;
int task[] = { 1, 2, 3, 87, 93, 82, 92, 86, 95 };
int i = 0;
if (!init(pq, task, sizeof(task) / sizeof(task[0]))) {
fprintf(stderr, "Failed to initialized the heap\n");
exit(-1);
}
for (i = 0; i < pq.size; i++) {
printf("the %dth task:%d\n", i, pq.arr[i]);
}
//Execute the sorting
heapSort(pq);
printf("The sorting result is:");
for (int i = 0; i < sizeof(task) / sizeof(task[0]); i++)
{
printf(" %d", task[i]);
}
system("pause");
return 0;
}