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 @   再次路过之  阅读(206)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示