排序
1.冒泡排序与插入排序、直接选择排序过程
#include<iostream>
using namespace std;
typedef int KeyType;
typedef int InfoType;
typedef struct
{
KeyType key;
InfoType data;
}RecType;
void InsertSort(RecType R[],int n)
{
int i,j;
RecType tem;
for(i=1;i<n;i++)
{
tem=R[i];
j=i-1;
cout<<endl;
cout<<"进行第"<<i<<"趟排序"<<endl;
while(j>=0 && tem.key<R[j].key)
{
R[j+1]=R[j];
j--;
cout<<R[j].key<<"与"<<R[j+1].key<<"进行交换"<<" ";
}
R[j+1]=tem;
}
}//插入排序
void BubbleSort(RecType R[],int n)
{
int i,j;
bool exchange;
RecType tmp;
for(i=0;i<n-1;i++)
{
cout<<endl;
cout<<"进行第"<<i+1<<"趟排序"<<endl;
for(j=n-1;j>i;j--)
{
exchange=false;
if(R[j].key<R[j-1].key)
{
tmp=R[j];
R[j]=R[j-1];
R[j-1]=tmp;
exchange=true;
cout<<R[j].key<<"与"<<R[j-1].key<<"进行交换"<<" ";
}
}
if(!exchange)
{
cout<<"不再需要交换,排序完成"<<endl;
return;
}
}
}//冒泡排序
void SelectSort(RecType R[],int n)
{
int i,j,k;
RecType tmp;
for(i=0;i<n-1;i++)
{
k=i;
cout<<"进行第"<<i+1<<"趟排序"<<endl;
cout<<endl;
for(j=i+1;j<n;j++)
{
if(R[j].key<R[k].key)
k=j;
}
if(k!=i)
{
tmp=R[i];
R[i]=R[k];
R[k]=tmp;
cout<<R[i].key<<"与"<<R[k].key<<"进行交换"<<" ";
}
}
}//直接选择排序
void SetRecType(RecType R[],int key[],int data[],int n)
{
for(int i=0;i<n;i++)
{
R[i].key=key[i];
R[i].data=data[i];
}
}
int main()
{
cout<<"插入排序"<<endl;
RecType r1[10];
int n=10;
int r1data[10]={9,8,7,6,5,4,3,2,1,0};
int r1key[10]={9,8,7,6,5,4,3,2,1,0};
SetRecType(r1,r1key,r1data,n);
InsertSort(r1,10);
cout<<endl;
cout<<endl;
cout<<"冒泡排序"<<endl;
RecType r2[10];
int r2data[10]={9,8,7,6,5,4,3,2,1,0};
int r2key[10]={9,8,7,6,5,4,3,2,1,0};
SetRecType(r2,r2key,r2data,n);
BubbleSort(r2,10);
cout<<endl;
cout<<endl;
cout<<"直接选择排序"<<endl;
RecType r3[10];
int r3data[10]={9,8,7,6,5,4,3,2,1,0};
int r3key[10]={9,8,7,6,5,4,3,2,1,0};
SetRecType(r3,r3key,r3data,n);
SelectSort(r3,10);
return 0;
}