在看数据结构时看到了上学期学到的两种排序方法:(1)选择法排序 ;(2)起泡法(冒泡法)排序。所以写了一个程序温习了一下。为了让程序更有交互性,用上了刚学的动态定义数组,即顺序表的创建。
程序如下:
#include <iostream>//动态定义数组和运用初学者常考到的两种排序法进行排序
using namespace std;
typedef struct
{
int *a;
int size;
}List;
void initial(List &L)
{
int n;
cout<<"1th: enter the size of the array:"<<endl;
cin>>n;
L.a=(int *)malloc(n*sizeof(int));
cout<<"2th: please input the array a[]:";
cout<<endl;
for(int i=0;i<n;i++)
{
cin>>L.a[i];
}
cout<<"the array you type in is:"<<endl;
for (int j=0;j<n ;j++ )
{
cout<<L.a[j]<<" ";
}
L.size=n;
}
void sort(List &L,int );//选择法排序
void BubbleSort(List &L);//冒泡法排序;
int main()
{
List L;
char g;
initial(L);
cout<<"用冒泡法排序B,还是用选择法排序S:注意是大写的\n";
cin>>g;
switch(g)
{
case('B'): BubbleSort(L);break;
case('S'):sort(L,L.size);break;
default: cout<<"您的输入有误!!!";
}
cout<<"the sorted array is:"<<endl;
for(int j=0;j<L.size;j++)
{
cout<<L.a[j]<<" ";
}
cout<<endl;
return 0;
}
void sort(List &L,int n)//选择法进行排序
{
for(int j=0;j<n-1;j++)
{
int i=j;
for (int k=j+1;k<n ;k++ )
{
if(L.a[k]<L.a[i])
i=k;
}
int temp=L.a[j];
L.a[j]=L.a[i];
L.a[i]=temp;
}
}
void BubbleSort(List &L)//冒泡法排序
{
bool change=true;
for(int i=L.size-1;i>0&&change;i--)
{
change=false;
for(int j=0;j<i;j++)
{
if(L.a[j]>L.a[j+1])
{
int t=L.a[j];
L.a[j]=L.a[j+1];
L.a[j+1]=t;
change=true;
}
}
}
}
2011年10月4日 14:35:02 记下。