冒泡排序Bubble Sort

目录

 Basic concept of sorting

 Algorithm Complexity

Code Implementation 

 Difference with selection sorting


Basic concept of sorting

Choose the first one and compare it with the second one, the bigger one will be put at a higher level, and be used to compare with the next one. Finally, the maximum will come to the top.

从最下面的元素开始,向上比较,每次选取较大的元素放上面的位置,最终最大的元素放在最上面。就像在冒泡。每次选取两者中较大的值,而不是选定一个最大值与其他元素比较。

for instance: 5>2, swap 5 and 2; 5<7, remain unchange; 7>6, swap 7 and 6; swap 7 and 1; swap 7 and 4; swap 7 and 3. 

 Algorithm Complexity

the best case

if the array in right oreder, only need one round of sorting, compare two adjacent相邻的 elements

 the worst case

 if the array in reverse order, need n rounds, and complexity is (0+n)*n/2 → O(n^2)

Code Implementation 

因为每次从最下面开始向上比较,所以限制length长度,不是i=0开始循环。

void bubble_sort(int arr[], int length){
    //外层循环:逐趟扫描
    //i>1的原因:只有一个元素的数组自然有序
    for(int i = length; i>1; i--){
        int swapped = 0; // 是否发生了变化的标志
        //一趟扫描,从0——i为一趟扫描,比到最后剩下一个最大的元素。
        for(int j=1; j<i; j++){
            //每次下面的元素与上面的元素比较,如果下面的大,就交换位置。
            if arr[j-1] > arr[j]{
                swap(&arr[j-1], &arr[j]);
                swapped = 1;
            }            
        }
        print_arr(arr, length, swapped);
        if(!swapped) break; //如果没有交换发生,结束
        
    }
}
@param arr
@param length
@param swapped
void print_arr(int arr[], int length, int swapped)
{
    for(int i=0; i < length; i++)
    {
        printf("%d", arr[i]);
    }
    printf("%s\n", swapped? "swapped" : "not swapped");
}




int main(int argc, char const % argv[])
{
    int arr[] = {5,2,7,6,1,4,3};

    print_arr(arr, 7, 0);

    bubble_sort(arr, 7);

    return 0;
}

 

 Difference with selection sorting

we compare two adjacent相邻的 elements, put the bigger one upper, not choose a maximum to compare with each one.

in every round , there may be more than one element move, but in selection sorting, just one element moves in one round. 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值