堆排序

堆排序

很久没更了,来一发
堆排序主要用到了大顶堆和小顶堆,建堆后将堆定元素和未排序序列最后一个元素交换则已排序序列多一个直到号元素结束

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
#include<stdio.h>
typedef int Elemtype;
//建立大顶堆
void HeapAdjust(Elemtype a[],int i,int len){//i是待调整为大顶堆数组的起点,len结束
int child;
int temp;
for(;i*2+1<len;i=child){
child=i*2+1;//子节点位置
if(child<len-1&&a[child+1]>a[child])
child++;//获得左右孩子中大的位置
if(a[i]<a[child]){//如果比父节点打就和父节点替换
temp=a[i];
a[i]=a[child];
a[child]=temp;
}else
break;//否则退出;
}
}
//用大顶堆开始堆排序
void HeapSort(Elemtype a[],int len){
int i;
int temp;
//调整序列前半部分成大顶堆,第一个元素为最大值
for(i=(len/2-1);i>=0;i--){
HeapAdjust(a,i,len);
}
for(i=len-1;i>0;i--){
temp=a[0];
a[0]=a[i];
a[i]=temp;
HeapAdjust(a,0,i);//i是因为后面n-i个已经有序
}
}
int main(){
Elemtype a[11];
int len =10;
for(int i=0;i<len;i++){
scanf("%d",&a[i]);
}
HeapSort(a,len);
for(int i=0;i<len;i++){
printf("%d=%d\n",i,a[i]);
}
return 0;
}


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!