c++冒泡排序法

// 冒泡排序法.cpp 
//第一个数依次和相邻的数对比,大的数放第二位,直到把数排列成由小到大。

#include <iostream>
using namespace std;


int main()
{
    int arr[] = { 4,2,8,5,7,1,3,9,12,15,17,21,24,16,78,90 };

    cout << "排序前:" << endl;
    int index = size(arr);
    //cout << index;
    for (int i = 0; i < index; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
    cout << endl;
    //开始冒泡排序,排序的总轮数等于元素个数-1;
   
    for (int i = 0; i < index - 1; i++)
    {
        //内层对比次数 = 元素个数 - 当前轮数-1;
        for (int j = 0; j < 9 - i - 1; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                //交换代码;
                int temp = 0;
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;

            }

        }

    }
    cout << "排序后:" << endl;
    for (int i = 0; i < index; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
    cout << endl;
    system("pause");
    return 0;
}

结果:

排序前:
4 2 8 5 7 1 3 9 12 15 17 21 24 16 78 90

排序后:
1 2 3 4 5 7 8 9 12 15 17 21 24 16 78 90

请按任意键继续. . .

 

posted @ 2022-08-05 21:48  再次路过之  阅读(165)  评论(0编辑  收藏  举报