您的位置:首页 > 其它

冒泡排序的有趣使用

2014-05-27 11:02 267 查看
/*
将一个互不相同的四位数,把所有的数值从小到大排序后得到a,从大到小排序后得到b,然后

用b-a替换原来的数,并继续操作。

*/

#include<iostream>
#include<string.h>
using namespace std;
void print(int s[],int n)
{for(int i=0;i<4;i++)
cout<<s[i]<<'\t';
cout<<endl;
}
int main()
{
int s[4];
int max[4],min[4];
int t;
int count=0;
cout<<"input the number is: "<<endl;
for(int i=0;i<4;i++)
cin>>s[i];
while(count<4){
memcpy(max,s,sizeof(s));
memcpy(min,s,sizeof(s));
//sort:
//from small to big
for(int j=1;j<=4;j++)//比较n-1趟
for(int k=0;k<4-j;k++)//每趟n-i次
if(min[k]>min[k+1])
{
t=min[k];
min[k]=min[k+1];
min[k+1]=t;
}
//from big to small
for(int a=1;a<=4;a++)//此处可以直接使用上一排好序的反序,而无需再使用冒泡排序
for(int b=0;b<4-a;b++)
if(max[b]<max[b+1])
{
t=max[b];
max[b]=max[b+1];
max[b+1]=t;
}
//compute substruction
cout<<"the min is: "<<endl;
print(min,4);
cout<<"the max is: "<<endl;
print(max,4);
int res=max[0]*1000+max[1]*100+max[2]*10+max[3]-min[0]*1000-min[1]*100-min[2]*10-min[3];//可将数组定义为字符串数组,这样可以方便很多!
cout<<"the res= "<<res<<endl;
for(int x=3;x>=0;x--)
{
s[x]=res%10;
res=res/10;
}
cout<<"the result is: "<<endl;
print(s,4);
count++;
}
return 0;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: