-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeapSort.c
86 lines (80 loc) · 2.39 KB
/
HeapSort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <stdio.h>
#include <stdlib.h>
#include "HeapSort.h"
void ArrayHeapSort(SDataType* arr, int len) //基于数组的堆排序
{
int i, j, k;
SDataType temp;
for(i = len/2 - 1; i >= 0; i--) //将arr[0,len-1]建成大根堆
{
while(2 * i + 1 < len) //第i个结点有右子树
{
j = 2 * i + 1;
if((j + 1) < len)
{
if(arr[j].totalcount > arr[j+1].totalcount) //左子树小于右子树,则需要比较右子树
{
j++; //序号增加1,指向右子树
}
}
if(arr[i].totalcount > arr[j].totalcount) //比较i与j为序号的数据
{
temp = arr[i]; //交换数据
arr[i] = arr[j];
arr[j] = temp;
i = j; //堆被破坏,需要重新调整
} else { //比较左右子树结点均大则堆未破坏,不再需要调整
break;
}
}
}
for(i = len - 1; i > 0; i--)
{
temp = arr[0]; //与i个记录交换
arr[0] = arr[i];
arr[i] = temp;
k = 0;
while(2 * k + 1 < i) //第i个结点有右子树
{
j = 2 * k + 1;
if((j + 1) < i)
{
if(arr[j].totalcount > arr[j+1].totalcount) //左子树小于右子树,则需要比较右子树
{
j++; //序号增加1,指向右子树
}
}
if(arr[k].totalcount > arr[j].totalcount) //比较i与j为序号的数据
{
temp = arr[k]; //交换数据
arr[k] = arr[j];
arr[j] = temp;
k = j; //堆被破坏,需要重新调整
} else { //比较左右子结点均大则堆未破坏,不需要调整
break;
}
}
}
}
void HeapSort(PNode head) //堆排序
{
int len = 0;
SDataType* arr = NULL;
if(head == NULL)
{
printf("排序失败,链表为空!\n");
return;
}
len = ListLength(head);
arr = (SDataType*)malloc(sizeof(SDataType) * len);
if(arr == NULL)
{
printf("申请内存失败!\n");
return;
}
List2Array(head, arr);
ArrayHeapSort(arr, len);
head = Array2List(head, arr, len);
free(arr);
return;
}