[算法]冒泡排序

早过忘川 提交于 2019-12-02 07:00:45

时间复杂度O(n^2)
基本思想:类似于冒气泡,将最大的冒到最上面。有两个指针,一个指着当前需要排序的序列,一个指着最后,然后慢慢往上冒。

#include <QCoreApplication>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

void swap(int &a,int &b)
{
    int temp=a;
    a=b;
    b=temp;
}
void bubbleSort(int a[],int size)
{
    for(int i=0;i<size;i++)
    {
        for(int j=size-1;j>=i+1;j--)
        {
            if(a[j]<a[j-1])
                swap(a[j],a[j-1]);
        }
    }
}
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    int A[5]={1,3,2,5,4};
    bubbleSort(A,5);
    for(auto s:A)
    {
        cout<<s<<" ";
    }
    cout<<endl;

    return a.exec();
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!