首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >C/C++ 常用算法手册(纯代码)

C/C++ 常用算法手册(纯代码)

作者头像
程序员小涛
发布2022-05-07 16:02:44
发布2022-05-07 16:02:44
5250
举报
文章被收录于专栏:涛的程序人生涛的程序人生

项目在Github上,不定期更新。

冒泡排序

代码语言:javascript
复制
#include <iostream>
#include <array>
#include <cstdlib>
#include <ctime>

using namespace std;

constexpr int SIZE = 10;

void BubbleSort(array<int, SIZE>& arr)
{
    int length = arr.size();
    for(int i = 0; i < length; i ++)
    {
        for(int j = length - 1; j > i; j--)
        {
            if(arr[j-1] > arr[j])
            {
                int temp = arr[j-1];
                arr[j-1] = arr[j];
                arr[j] = temp;
            }
        }
        cout << "第" << i << "步的排序结果: ";
        for(auto iter = arr.begin(); iter != arr.end(); ++iter)
        {
            cout << *iter << " ";
        }
        cout << endl;
    }
}

int main()
{
    array<int, SIZE> arr = {0};

    srand(time(NULL));
    for(int i = 0; i < SIZE; i++)
    {
        arr[i] = rand() / 1000 + 100;
    }

    cout << "排序前的数组为:" << endl;
    for(auto iter = arr.begin(); iter != arr.end(); ++iter)
    {
        cout << *iter << " ";
    }
    cout << endl;

    BubbleSort(arr);


    cout << "排序后的数组为:" << endl;
    for(auto iter = arr.begin(); iter != arr.end(); ++iter)
    {
        cout << *iter << " ";
    }
    cout << endl;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-03-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档