每一趟在n-i+1个记录中选取关键字最小的记录,并与当前序列中的第i个记录交换,作为有序序列中第i个记录
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAXSIZE 20
typedef int KeyType;
typedef int InfoType;
typedef struct
{
KeyType key;
InfoType otherinfo;
}RedType;
typedef struct
{
RedType r[MAXSIZE+1];
int length;
}SqList;
int LT(KeyType a,KeyType b);
void Swap(SqList *L,int low,int high);
void SelectSort(SqList *L);
int SelectMinKey(SqList *L,int i);
void HeapAdjust(SqList *L,int s,int m);
void HeapSort(SqList *L);
int main()
{
SqList *L,*L1,*L2,*L3,*L4;
L=(SqList *)malloc(sizeof(SqList));
L1=(SqList *)malloc(sizeof(SqList));
L2=(SqList *)malloc(sizeof(SqList));
L3=(SqList *)malloc(sizeof(SqList));
L4=(SqList *)malloc(sizeof(SqList));
int i;
printf("需排序的项数为:");
scanf("%d",&L->length);
for(i=0;i<L->length;i++)
{
printf("please input the number:");
scanf("%d",&L->r[i+1].key);
}
*L1=*L2=*L3=*L4=*L;
SelectSort(L1);
HeapSort(L2);
printf("选择排序的结果:");
for(i=0;i<L1->length;i++)
{
printf("%d ",L1->r[i+1].key);
}
printf("\n");
printf("堆排序的结果:");
for(i=0;i<L2->length;i++)
{
printf("%d ",L2->r[i+1].key);
}
printf("\n");
return 0;
}
int LT(KeyType a,KeyType b)
{
return a<b;
}
void Swap(SqList *L,int low,int high)
{
RedType *t;
t=(RedType *)malloc(sizeof(RedType));
*t=L->r[low];
L->r[low]=L->r[high];
L->r[high]=*t;
free(t);
}
/*简单选择排序,时间复杂度为n^2*/
void SelectSort(SqList *L)
{
int i,j;
for(i=1;i<L->length;i++)
{
j=SelectMinKey(L,i);
if(i!=j)
Swap(L,i,j);
}
}
int SelectMinKey(SqList *L,int i)
{
int k,t=i;
for(k=i+1;k<=L->length;k++)
if(L->r[t].key>L->r[k].key)
t=k;
return t;
}
/*树形选择排序/锦标赛排序*/
/*时间复杂度为nlogn,但是所需辅助空间较多,因此提出另一种堆排序*/
/*堆排序:即使最坏情况下,时间复杂度为nlogn*/
/*筛选:即s至m序列中,除s外均满足堆定义,将s自顶向下调整,以满足堆定义*/
void HeapAdjust(SqList *L,int s,int m)
{
int j;
RedType rc;
rc=L->r[s];
for(j=2*s;j<=m;j*=2)
{
if(j<m && LT(L->r[j].key,L->r[j+1].key))
j++;
if(!LT(rc.key,L->r[j].key))
break;
L->r[s]=L->r[j];
s=j;
}
L->r[s]=rc;
}
void HeapSort(SqList *L)
{
int i;
for(i=L->length/2;i>0;i--)
HeapAdjust(L,i,L->length);
for(i=L->length;i>1;i--)
{
Swap(L,1,i);
HeapAdjust(L,1,i-1);
}
}