堆排序的实现:
在顺序结构上完成,先建堆然后重建堆,最后实现全部排序
(个人作法,仅供参考)
#include<stdio.h>
#include<stdlib.h>
#define max 100000
void HeapAdjust(int heap[],int k,int m)
{
int i,j,finished;
int temp;
temp=heap[k];
i=k;
j=2*i;
finished=false;
while(j<=m&&!finished)
{
if(j<m&&heap[j]>heap[j+1])j=j+1;//筛选
if(temp<=heap[j])finished=true;
else
{
heap[i]=heap[j];
i=j;
j=2*i;
}
}
heap[i]=temp;
}
void HeapAdjust2(int heap[],int k,int m)
{
int i,j,finished;
int temp;
temp=heap[k];
i=k;
j=2*i;
finished=false;
while(j<=m&&!finished)
{
if(j<m&&heap[j]<heap[j+1])j=j+1;//筛选
if(temp>=heap[j])finished=true;
else
{
heap[i]=heap[j];
i=j;
j=2*i;
}
}
heap[i]=temp;
}
void CreateHeap(int heap[],int length)
{
int i,n=length;
for(i=n/2;i>=1;--i)
HeapAdjust(heap,i,n);
}
void CreateHeap2(int heap[],int length)
{
int i,n=length;
for(i=n/2;i>=1;--i)
HeapAdjust2(heap,i,n);
}
void HeapSort(int heap[],int length)//对heap[1...n]进行堆排序
{
int temp,i,n;
CreateHeap(heap,length);
n=length;
for(i=n;i>=2;--i)
{
temp=heap[1];//将堆顶记录和堆中的最后一个记录互换
heap[1]=heap[i];
heap[i]=temp;
HeapAdjust(heap,1,i-1);//进行调整,使heap[1...i-1]变成堆
}
}
void HeapSort2(int heap[],int length)//对heap[1...n]进行堆排序
{
int temp,i,n;
CreateHeap2(heap,length);
n=length;
for(i=n;i>=2;--i)
{
temp=heap[1];//将堆顶记录和堆中的最后一个记录互换
heap[1]=heap[i];
heap[i]=temp;
HeapAdjust2(heap,1,i-1);//进行调整,使heap[1...i-1]变成堆
}
}
void PrintfHeap(int heap[],int length)
{
int i;
for(i=1;i<=length;i++)
printf("%d ",heap[i]);
printf(" ");
}
int main()
{system("color cf");
int heap[max];
int n,i,choice;
printf(" 堆排序功能选项 ");
printf(" 1.输入一个新序列并进行堆排序 ");
printf(" 2.输出当前序列大顶堆排序 ");
printf(" 3.输出当前序列小顶堆排序 ");
printf(" 4.退出堆排序 ");
loop1: printf("请选择你的操作:");
scanf("%d",&choice);
switch(choice)
{
loop2: case 1:
printf("请输入序列的个数:");
scanf("%d",&n);
printf("请依次输入将要进行堆排序的元素: ");
for(i=1;i<=n;i++)
scanf("%d",&heap[i]);
heap[0]=n;
goto loop1;
loop3: case 2:
HeapSort(heap,n);
printf("从大到小排序: ");
PrintfHeap(heap,heap[0]);
goto loop1;
loop4: case 3:
HeapSort2(heap,n);
printf("从小到大排序: ");
PrintfHeap(heap,heap[0]);
goto loop1;
case 4: printf("欢迎再来 "); break;
default:
exit(0);
}
return 0;
}
}
2.功能界面