C++数据结构--选择排序

来源:互联网 发布:软件专业毕业设计题目 编辑:程序博客网 时间:2024/05/27 20:49
#include <stdio.h>
typedef int InfoType;
#define n 5    //假设的文件长度,即待排序的记录数目
typedef int KeyType; //假设的关键字类型
typedef struct { //记录类型
KeyType key; //关键字项
InfoType otherinfo;//其它数据项,类型InfoType依赖于具体应用而定义
} RecType;
typedef RecType SeqList[n+1]; //SeqList为顺序表类型,表中第0个单元一般用作哨兵


void main()
{
void SelectSort(SeqList R);
int i;
SeqList R;
printf("请输入欲排序的数:");
for (i=1;i<=n;i++)
scanf("%d",&R[i].key);
printf("排序前:");
for (i=1;i<=n;i++)
printf("%d ",R[i].key);
printf("\n");
SelectSort(R);
printf("排序后:");
for (i=1;i<=n;i++)
printf("%d ",R[i].key);
printf("\n");
}


//对R[1..n]进行直接选择排序,用R[0]做暂存单元
void SelectSort(SeqList R)
{
int min=0;
void swap(SeqList R,int i,int j);
for(int i=1;i<n;i++)
{
min=i;
for(int j=i+1;j<=n;j++)
{
if(R[min].key>R[j].key)
min=j;


}
if(min!=i)
swap(R,i,min);




}
}


void swap(SeqList R,int i,int j)
{


RecType temp=R[i];
R[i]=R[j];
R[j]=temp;


}



运行结果:



原创粉丝点击