C++冒泡排序

79 阅读1分钟
#include<iostream>
using namespace std;

//冒泡排序
//排序总轮数 = 元素个数 - 1
//每轮对比次数 = 元素个数 - 排序轮数 - 1

int main(){
    
    //利用冒泡排序实现升序序列
    int arr[9] = {4,2,3,6,8,7,5,0,9};

    //开始冒泡排序
    //排序总轮数 = 元素个数 - 1
    for (int i = 0; i < 9 - 1; i++)
    {
        //内层循环对比次数 = 元素个数-当前轮数 - 1
        for (int j = 0; j < 9 -i -1; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    //排序后结果
    for (int i = 0; i < 9; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
    system("pause");
    return 0;
}


image.png