人人都来学算法 之 冒泡排序

来源:互联网 发布:atv610变频器编程手册 编辑:程序博客网 时间:2024/06/07 21:36


冒牌排序是大学学习数据结构最先学习的排序算法,平均时间效率较快速排序等方法效率低,但是算法也最简单,就是每次遍历都把最大的元素(升序)交换到当前的最后一个位置。

这个算法也是笔试中最最常见,难度也是考察编程能力的最低要求。



#include <iostream>

using std::cout;
using std::endl;


void bubbleSort(int data[], int count)
{
    bool isChanged = true;
    for(int i=0; i<count; ++i)
    {
        for(int j=0; j<count-i-1; ++j)
        {
            int x;
            if(data[j]>data[j+1])
            {
                x = data[j];
                data[j]=data[j+1];
                data[j+1]=x;
                isChanged = true;
            }
        }
    }
}


int main()
{
    const int count = 10;
    int data[count] = {7,2,6,4,0,9,5,1,3,8};
    bubbleSort(data, count);

    for(int i = 0; i< count; i++)
    {
        cout<<data[i]<<endl;
    }
    getchar();
}







原创粉丝点击