冒泡排序的有趣使用

/*
  将一个互不相同的四位数,把所有的数值从小到大排序后得到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;}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值