0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## 算法学习之冒泡排序，6174问题

6174问题

“冒泡排序”

```#include <conio.h>
#include<stdio.h>
#include<string.h>
int get_next(int x){
int a,b,n;
char s[10];
//转化成字符串
sprintf(s,"%d",x);
n = strlen(s);
//冒泡排序
for(int i = 0;i<n;i++){
for(int j = i+1;j<n;j++){
if(s[i]>s[j]){//第i个跟之后的所有进行比较，最小的留下
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
}
sscanf(s,"%d",&b);
//字符串反转
for(int i=0;i<n/2;i++){
char t = s[i];
s[i] = s[n-1-i];
s[n-1-i] = t;
}
sscanf(s,"%d",&a);
return a - b;
}
//逐个生成各个数
int num[2000],count;
int main(){
scanf("%d",&num[0]);
printf("%d",num[0]);
count = 1;
for(;;){
//生存并输出下一个数
num[count] = get_next(num[count-1]);
printf("->%d",num[count]);
int found = 0;
for(int i=0;i<count;i++){
if(num[i] == num[count]){
found = 1;break;
}
}
if(found){
break;
}
count++;
}
printf("\n");
getch();
return 0;
}```

冒泡排序

```#include <conio.h>
#include<stdio.h>
#include<string.h>
int bubble_sort(int x){
int r,n;
char s[10];
sprintf(s,"%d",x);
n = strlen(s);
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(s[i]>s[j]){
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
}
sscanf(s,"%d",&r);
return r;
}

int main(){
int num,r;
scanf("%d",&num);
printf("%d",num);
r = bubble_sort(num);
printf("\n");
printf("排序后的结果为%d",r);
getch();
return 0;
}```

+ 关注

corcosa 16042人浏览