现在的位置: 首页 > 综合 > 正文

冒泡排序

2018年09月17日 ⁄ 综合 ⁄ 共 838字 ⁄ 字号 评论关闭

/*
* 冒泡排序。
递增排序:从数组最底部的数据向上两两比较,小的数据冒泡。这样,浮在最上面的就是最小的数据。
递减排序:同理
*/

#include <iostream>
using namespace std;

 

void xf_Swap(int& x, int& y)
{
    int temp = x;
    x = y;
    y = temp;
}

 
void xf_BubbleSortIncrease(int ary[], int count)
{
    for(int i = count;i>0;--i)
    {
        for(int j = count-2; j >= 0; --j)
        {
            if(ary[j] > ary[j + 1])
            {  
                xf_Swap(ary[j],ary[j + 1]);
            }
        }
    }
 
}

void xf_BubbleSortDecrease(int ary[], int count)
{
    for(int i = count;i>0;--i)
    {
        for(int j = count-2; j >= 0; --j)
        {
            if(ary[j] < ary[j + 1])
            {  
                xf_Swap(ary[j],ary[j + 1]);
            }
        }
    }
 
}

 
int main(int arc, char* const argv[])
{
    //测试数据
    int ary[] = {9,8,10,3,5,6,4,7,2,1};
    //冒泡排序
    //xf_BubbleSortIncrease(ary, 10);
    xf_BubbleSortDecrease(ary, 10);
    //打印排序结果
    int i;
    for(i = 0; i < 10; i++)
        cout << ary[i] << endl;
 return 0;
}

【上篇】
【下篇】

抱歉!评论已关闭.