冒泡排序的有趣使用
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;}
相关文章推荐
- 使用冒泡对数组进行排序
- 输入三个数字使用指针进行排序(冒泡原理)
- 使用冒泡倒序排序
- C#中使用委托对字符串进行冒泡排序案例
- Collections.sort()排序使用方法
- 使用XSL实现在客户端的排序操作
- 使用接口排序(2)
- [原创]使用DataList分页显示数据,双向排序,添加checkbox控件。
- 使用XSL实现在客户端的排序操作
- 使用XPathExpression类对XML进行排序
- 单向链表排序(冒泡)
- 使用std:sort排序较复杂数据
- MSHFlexGrid1使用技巧(二)[如何让MSHFlexGrid实现点击列标题排序]
- 使用ASP.NET Atlas SortBehavior实现客户端排序
- 排序:冒泡法
- 使用Arrays.sort(..)方法進行排序
- MSHFlexGrid1使用技巧(二)[如何让MSHFlexGrid实现点击列标题排序]
- 使用vb.net 对 Windows Form 按列排序 ListView 项目
- 很有趣的一篇文章:不使用Linux的五大理由
- 冒泡排序方法