#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
typedef int ElemType;
typedef struct {
ElemType *ele;
int length;
} Table;
void initTable(Table &table, int length) {
table.ele = (ElemType *) malloc(sizeof(ElemType) * length);
table.length = length;
srand(time(NULL));
for (int i = 0; i < table.length; i++) {
table.ele[i] = rand() % 100;
}
}
void printTable(Table table) {
for (int i = 0; i < table.length; i++) {
printf("%3d", table.ele[i]);
}
}
void swap(int &a, int &b) {
int temp;
temp = a;
a = b;
b = temp;
}
//把某个子树调整为大根堆
void adjust(int *list, int i, int length) {
int dad = i;//父节点索引
int son = 2 * dad + 1;//左孩子索引
while (son < length) {
if (son + 1 < length && list[son] < list[son + 1]) {
son++;
}
if (list[son] > list[dad]) {//右>父节点
swap(list[son], list[dad]);
dad = son;//son重新作为dad去判断下面的子树是否符合大根堆
son = 2 * dad + 1;
} else {
break;
}
}
}
void heapSort(int *list, int length) {
int i, j, min;
for (i = length / 2 - 1; i >= 0; i--) {//从最后的根节点开始调
adjust(list, i, length);
}
swap(list[0], list[length - 1]);
for (i = length - 1; i > 1; i--) {
adjust(list,0,i);//调整剩余元素变为大根堆
swap(list[0], list[i - 1]);
}
}
int main() {
Table table;
initTable(table, 10);
printTable(table);
printf("\n");
heapSort(table.ele, 10);
printTable(table);
return 0;
}
17.4堆排序
最新推荐文章于 2024-08-31 22:19:14 发布