冒泡排序(Bubble Sort)

theory

  1. 每一轮循环都会比较一个数和他相邻的数(每次两两比较),然后根据大小交换与否,后面的数变得有序
  2. 需要n-1轮循环
  3. 实际上当某一轮循环没有进行任何操作的时候就说明有序了,可以跳出循环了,但是需要增加标志位(flag),所以我还是直接循环下去吧,每一次标志位的判断和赋值也同样增加了基础操作
  4. 直接上图就很简洁明了了
    在这里插入图片描述

code

/*
 * @Author: 鱼香肉丝没有鱼
 * @Date: 2021-11-13 16:17:51
 * @Last Modified by:   鱼香肉丝没有鱼
 * @Last Modified time: 2021-11-13 16:17:51
 */

#include <iostream>
using namespace std;

void swap(int& a, int& b)  //引用可以直接交换原本的值
{
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int num[12] = {23, 45, 17, 11, 13, 89, 72, 26, 3, 17, 11, 13};
    int n = 12;
    int i, j;
    for(i = 0; i < n - 1; i++) {
        for(j = 1; j < n - i; j++) {  //
            if(num[j - 1] > num[j])  //每次比较第j个数和他前面的那个数,n-i之后的数都是有序的了
                swap(num[j - 1], num[j]);
        }
    }
    cout << "排序后的数组为:" << endl;
    for(int i = 0; i < n; i++)
        cout << num[i] << ' ';
    cout << endl;

    return 0;
}

增加 flag 版本
/*
 * @Author: 鱼香肉丝没有鱼
 * @Date: 2021-11-13 16:17:51
 * @Last Modified by:   鱼香肉丝没有鱼
 * @Last Modified time: 2021-11-13 16:17:51
 */

#include <iostream>
using namespace std;

template <typename Type>
void Swap(Type& a, Type& b) {
    Type tmp = a;
    a = b;
    b = tmp;
}

template <typename Type>
void Print(Type* arr, int n) {
    if(n >= 0)
        cout << arr[0];
    for(int i = 1; i < n; i++)
        cout << " " << arr[i];
    cout << endl;
}

template <typename Type>
void BubbleSort(Type* num, int n) {
    int flag = 1;
    for(int i = 0; i < n - 1, flag; i++) {
        flag = 0;
        for(int j = 1; j < n - i; j++) {  //
            if(num[j - 1] > num[j]) {  //每次比较第j个数和他前面的那个数,n-i之后的数都是有序的了
                flag = 1;
                Swap(num[j - 1], num[j]);
            }
        }
    }
}

int main() {
    int num[12] = {23, 45, 17, 11, 13, 89, 72, 26, 3, 17, 11, 13};
    int n = 12;

    BubbleSort(num, n);

    cout << "排序后的数组为:" << endl;
    Print(num, n);

    return 0;
}

summary

  1. 时间复杂度 O(n2)
  2. 是稳定的排序方法
  3. 可以增加一个flag标记,记录每一趟冒泡交换发生的次数,如果某一趟为0,那么数据就已经有序了,可以终止了
  4. 所有简单排序中速度最慢
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值