为面试做准备:冒泡算法steemCreated with Sketch.

in #bubble7 years ago

冒泡排序是排序算法中较为简单的一种,英文称为Bubble Sort。它遍历所有的数据,每次对相邻元素进行两两比较,如果顺序和预先规定的顺序不一致,则进行位置交换;这样一次遍历会将最大或最小的数据上浮到顶端,之后再重复同样的操作,直到所有的数据有序。

第一种:直接全部遍历


#include <stdio.h>
int main()
{
int data[10]={1,3,5,7,9,2,4,6,8,0};
int i=0;
int j=0;
int temp=0;

for(i=0;i<10;i++){

    for(j=0;j<9-i;j++){
        if(data[j]>data[j+1]){
        
            temp=data[j];
            data[j]=data[j+1];
            data[j+1]=temp;
        }
    }
} 

// 打印排序后的结果
for (i=0;i<10;i++){
printf("%d ",data[i]);
}
return 0;
}

第二种:假若给的数组已经排列好了,我们只要在第一趟循环过程中做个标记,若没有交换则直接跳出,不必去比较下一趟了。

#include <stdio.h>
int main()
{
int data[10]={1,3,5,7,9,2,4,6,8,0};
int i=0;
int j=0;
int temp=0;
int flag=0;
for(i=0;i<10;i++){
flag=1;
for(j=0;j<9-i;j++){
if(data[j]>data[j+1]){
flag=0;
temp=data[j];
data[j]=data[j+1];
data[j+1]=temp;
}
if(flag){
break;
}
}
}
// 打印排序后的结果
for (i=0;i<10;i++){
printf("%d ",data[i]);
}
return 0;
}

Sort:  

Hey @franklei! Glad to meet you here! Have you tried Partiko? It’s a really cool Steem app! You download it, login using your Steem account, and boom, you can use Steem on your phone!

What’s even cooler is that they reward you Partiko Points for using it, and you can cash it out for STEEM!

Join using this link: https://partiko.app/referral/vintage-m , and you will get 1000 Points as a bonus! Let’s see who can reach 30000 Points first!

Coin Marketplace

STEEM 0.13
TRX 0.34
JST 0.033
BTC 122138.66
ETH 4502.02
SBD 0.79