数据结构实训-各种排序

廉价感情. 提交于 2020-02-17 05:48:06

任务:用程序实现插入法排序、起泡法改进算法排序;利用插入排序和冒泡法的改进算法,将用户随机输入的一列数按递增的顺序排好。
  输入的数据形式为任何一个正整数,大小不限。
  输出的形式:数字大小逐个递增的数列。

#include<iostream>
using namespace std;

void InsertSort(int sort[],int n)
{
    int i,j,t;
	for(i=1;i<n;i++)
	{
	    if(sort[i]<sort[i-1])
		{
		    t=sort[i];
			j=i-1;
			do
			{
			    sort[j+1]=sort[j]; 
				j--; 
			}while(j>=0&&sort[j]>t);
			sort[j+1]=t; 
		}
	}
}

void BubbleSort(int sort[],int n)
{
    
	int i,j,t;
	bool ex;
	for(i=0;i<n;i++)
	{
	    ex=false;
		for(j=n-1;j>i;j--)
		    if(sort[j]<sort[j-1])
			{
			    t=sort[j];sort[j]=sort[j-1];sort[j-1]=t;
				ex=true; 
			}
		if(!ex) break; 
	}
}

int main()
{
    int n,i,choose;
    cout<<"请输入将要输入的数字的个数n:";
    cin>>n;
	int sort[n];
	for(i=0;i<n;i++)
	{
	    cout<<"第"<<i+1<<"个数字:";
		cin>>sort[i]; 
	}
	cout<<"请选择排序方式:1.插入法  2.起泡法改进算法"<<endl;
	leap21: 
	cin>>choose;
	switch(choose)
	{
	    case 1:InsertSort(sort,n);break; 
		case 2:BubbleSort(sort,n);break;
		default: cout<<"请输入1或2:";goto leap21;
	}
	cout<<"排序结果为:"; 
	for(i=0;i<n;i++)
	{
	    cout<<sort[i]<<" "; 
	}
	cout<<endl; 
}


仅作留档。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!