冒泡排序,选择排序,快速排序,插入排序,折半选择排序

#include<iostream>
#define MAX 1000
using namespace std;
//简单插入排序
void InsertSort(int a[],int len)
{
	for(int i=1;i<len;i++)
	{
		int j;
		int temp;
		for(j=i-1;(j>=0)&&(a[j]>a[i]);j--)
			;
		temp=a[i];
		for(int k=i-1;k>j;k--)
			a[k+1]=a[k];
		a[j+1]=temp;
	}
	for(int i=0;i<len;i++)
		cout<<a[i]<<" ";
	cout<<endl;
}
//折半插入排序
void BInsertSort(int a[],int len)
{
	for(int i=1;i<len;i++)
	{
		int low=0;
		int high=i-1;
		int m;
		while(low<=high)
		{
			m=(low+high)/2;
			if(a[m]>a[i])
				high=m-1;
			else
				low=m+1;
		}
		int temp=a[i];
		for(int k=i-1;k>high;k--)
			a[k+1]=a[k];
		a[high+1]=temp;
	}
	for(int i=0;i<len;i++)
		cout<<a[i]<<" ";
	cout<<endl;
}
//冒泡排序
void BubbleSort(int a[],int len)
{
	for(int i=0;i<len;i++)
	{
		int flag=false;
		for(int j=0;j<len-1-i;j++)
			if(a[j]>a[j+1])
			{
				int temp;
				temp=a[j];
				a[j]=a[j+1];
				a[j+1]=temp;
				flag=true;
			}
			if(!flag)
				break;
	}
	for(int i=0;i<len;i++)
		cout<<a[i]<<" ";
	cout<<endl;
}
//快速排序
void QuickSort(int a[],int low,int high)
{
	if(low>=high)
		return;
	int l=low;
	int r=high;
	int m=a[(low+high)/2];
	while(l<r)
	{
		while(a[l]<m)
			l++;
		while(m<a[r])
			r--;
		if(l<=r)
		{
			int temp;
			temp=a[l];
			a[l]=a[r];
			a[r]=temp;
			l++;
			r--;
		}
	}
	if(l<high)
		QuickSort(a,l,high);
	if(r>low)
		QuickSort(a,low,r);

}
//选择排序
void SelectSort(int a[],int len)
{
	for(int i=0;i<len;i++)
	{
		int minIndex=i;
		for(int j=i+1;j<len;j++)
		{
			if(a[j]<a[minIndex])
				minIndex=j;
		}
		if(i!=minIndex)
		{
			int temp;
			temp=a[i];
			a[i]=a[minIndex];
			a[minIndex]=temp;
		}
	}
}

void main()
{
	while(true)
	{
		int a[MAX];
		cout<<"请输入待排序的数组的长度:"<<endl;
		int len;
		cin>>len;
		cout<<"请输入数据:"<<endl;
		for(int i=0;i<len;i++)
			cin>>a[i];
		/*InsertSort(a,len);*/
		/*BInsertSort(a,len);*/
		/*BubbleSort(a,len);*/
		/*QuickSort(a,0,len-1);*/
		SelectSort(a,len);
		for(int i=0;i<len;i++)
			cout<<a[i]<<" ";
		cout<<endl;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值