【程序设计】
题目:
输入3个整数,按从大到小的顺序输出
注意:输出的数据使用 '\t' 隔开 。
样例:
输入三个整数2
1
3
3 2 1
请按任意键继续. . .
代码1(穷举):
#include <iostream>
using namespace std;
int main(){
int a,b,c;
cout<<"输入三个整数";
cin>>a>>b>>c;
if(a>=b&&b>=c)
{
cout<<a<<"\t"<<b<<"\t"<<c<<endl;
}
else if(a>=c&&c>=b)
{
cout<<a<<"\t"<<c<<"\t"<<b<<endl;
}
else if(b>=a&&a>=c)
{
cout<<b<<"\t"<<a<<"\t"<<c<<endl;
}
else if(b>=c&&c>=a)
{
cout<<b<<"\t"<<c<<"\t"<<a<<endl;
}
else if(c>=a&&a>=b)
{
cout<<c<<"\t"<<a<<"\t"<<b<<endl;
}
else
{
cout<<c<<"\t"<<b<<"\t"<<a<<endl;
}
return 0;
}
穷举优点:通俗易懂;
穷举缺点:倘若数据多了,情况数会爆炸(排列数A);
代码2(数组,冒泡排序):
#include <iostream>
using namespace std;
int main()
{
int a[3];
cout<<"输入三个整数";
for(int i=0;i<3;i++)
{
cin>>a[i];
}
int temp;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
{
if(a[j]<a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
for(int i=0;i<3;i++)
{
cout<<a[i]<<"\t";
}
cout<<endl;
return 0;
}
冒泡特点:写法经典,代码好记;
代码3(插入排序):
#include <iostream>
using namespace std;
int main(){
/**********Program**********/
int a[3],temp,i,j;
cout<<"输入三个整数";
for(i=0;i<3;i++)
{
cin>>a[i];
}
for(i=1;i<3;i++)
{
temp=a[i];
for(j=i-1;j>=0;j--)
{
if(a[j]<temp)
{
a[j+1]=a[j];
}
else
{
break;
}
}
a[j+1]=temp;
}
for(i=0;i<3;i++)
{
cout<<a[i]<<"\t";
}
cout<<endl;
/********** End **********/
return 0;
}
插排特点:类似扑克的插入,比较符合人的排序逻辑,时间复杂度O(n^2)和冒泡排序一样。