菜鸟学习c++—实现简单的冒泡排序和插入排序算法

本文介绍了冒泡排序和插入排序两种基本排序算法,并通过C++代码实例展示了这两种算法的具体实现过程。冒泡排序通过重复遍历待排序的数列,比较每对相邻项并交换顺序不当的元素来达到排序目的;而插入排序则是在每个输入数据时将其插入已排序序列的正确位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

冒泡排序和插入排序算法是两个简单易实现的排序算法,但工作效率低下,只适合做小规模数据的排序。


冒泡排序:根据自己的需求,每次排序时把序列中最大的数置于序列首或序列尾,经过多次排序得到有序序列。

#include <iostream>

using namespace std;

int main()

{

    void bubble_sort(int sample[]);

    int array[10];

    cout<<"please give sample array(size:10):"<<endl;

    for (int i=0; i!=10; i++)

    {

        cin>>array[i];

    }

    bubble_sort(array);

    for (int i=0; i!=10; i++)

    {

        cout<<array[i]<<"   "<<flush;

    }

}

void bubble_sort(int sample[])

{

    int mark;

    int times;

    int temp;

    for (times=0; times<=9; times++)

    {

        for (mark=0; mark+times<9; mark++)

        {

            if (sample[mark]>=sample[mark+1])

            {

                temp=sample[mark+1];

                sample[mark+1]=sample[mark];

                sample[mark]=temp;

            }

        }

    }

}

插入排序:每次输入数据时,将数据插入到序列中合适的位置,得到有序序列。

#include <iostream>

#include <string>

#include <vector>

using namespace std;

vector<int> base;

int main()

{

    int data;

    void Insertion_sort(int input);

    void display();

    cout<<" please enter data(press s to finish):"<<endl;

    cin>>data;

    base.push_back(data);

    while(cin>>data)

    {

    Insertion_sort(data);

    }

    display();

}


void Insertion_sort(int input)

{

    auto beg=base.begin();

    auto end=base.end();

    while(*beg>=input && beg!=end)

    {

        beg++;

    }

    base.insert(beg,input);

}

void display()

{

    auto beg=base.begin();

    auto end=base.end();

    while(beg!=end)

    {

        cout<<*beg++<<" "<<flush;

    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值