1 //简单选择排序
2 void SelectSort(ElemType A[], int n) {
3 int i, j, min,temp;
4 for (i = 1; i <= n-1; ++i) {
5 min = i;
6 for (j = i + 1; j <= n; ++j)
7 if (A[j] < A[min])
8 min = j;
9 if (min != i) {
10 temp = A[i];
11 A[i] = A[min];
12 A[min] = temp;
13 }
14
15 }
16 }
17
18 //重建堆过程(以大根堆为例)
19 void sift(ElemType A[], int k, int m) {
20 int i, j;
21 A[0] = A[k];
22 i = k;
23 j = 2 * i;
24 int finished = 0;
25 while (j <= m && !finished) {
26 if (j + 1 <= m && A[j] < A[j + 1])//若存在右子树,且右子树的关键字大,则沿右分支筛选
27 j = j + 1;
28 if (A[0] >= A[j])
29 finished = 1;//筛选完毕
30 else {
31 A[i] = A[j];
32 i = j;
33 j = 2 * i;
34 }
35 }
36 A[i] = A[0];//A[k]放入适当的位置
37 }
38 //最后一个非叶结点位于第n/2向下取整个位置,n为二叉树结点数目,依次筛选从第n/2向下取整个结点开始,逐层向上倒退,直到根结点
39 void crt_heap(ElemType A[], int n) {
40 //对数组建堆,n为数组的长度
41 int i;
42 for (i = n / 2; i >= 1; --i)
43 sift(A, i, n);
44 }
45 //堆排序
46 void HeapSort(ElemType A[], int n) {
47 ElemType temp;
48 crt_heap(A, n);//初始建堆
49 for (i = n; i >= 2; --i) {//堆尾与堆顶记录交换
50 temp = A[1];
51 A[1] = A[i];
52 A[i] = temp;
53 sift(A, 1, i - 1);//重建堆,剩余的i-1个元素整理成堆
54 }
55 }
//重建堆,以小根堆为例
void sifts(ElemType A[], int k, int m) {
int i, j;
A[0] = A[k];
i = k;
j = 2 * i;
finished = 0;
while (j <= m; && !finished) {
if (j + 1 <= m && A[j] > A[j + 1])
j++;
if (A[0]<=A[j])
finished = 1;
else {
A[i] = A[j];
i = j;
j = 2 * i;
}
}
A[i] = A[0];
}
void crt_heapl(ElemType A[], int n) {
int i;
for(i=n/2;i>=1;--i)
sifts(A,i,n)
}
努力的意义就是放眼望去以后都是喜欢的人和事......