franklei avatar

为面试做准备:冒泡算法

franklei

Published: 19 Mar 2019 › Updated: 19 Mar 2019为面试做准备:冒泡算法

为面试做准备:冒泡算法

冒泡排序是排序算法中较为简单的一种,英文称为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;
}

Leave 为面试做准备:冒泡算法 to:

Written by

love life and love myself

Read more #bubble posts


Best Posts From franklei

We have not curated any of franklei's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From franklei