动态定义数组和使用两种常用的排序法进行排序

在看数据结构时看到了上学期学到的两种排序方法:(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     记下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值