C++11写算法之冒泡排序

冒泡排序很形象,指从数组后面将更小的值慢慢浮到前面去,每遍历一趟使得最小值浮到最前面(指当前位置)。

这里有点小技巧,当某一次遍历过程中发现无交换,则说明此时数组已经排序完成,可提前退出。

时间复杂度:O(n^2)

空间复杂度:O(1)

此处应用了C++11的auto , lambda , static_assert 。

show me the code !

C++11写算法之冒泡排序
// #if __cplusplus < 201103L 
// #error "must be compiled under c++11 support platform!!!"
// #endif
#include <iostream>
#include <algorithm>
#include <iterator>
#include <cassert>
using namespace std;

void Swap(int& a, int& b)
{
    int tmp = a;
    a = b;
    b = tmp;
}
void BubbleSort(int varList[], const int size)
{
    if (!varList || size <= 1)
    {
        return;
    }
    bool sortedOK = false;
    for (int i = 0; i < size && !sortedOK; i++)
    {
        sortedOK = true;
        for (int j = size - 1; j >= i;j--)
        {
            if (varList[j-1] > varList[j])
            {
                Swap(varList[j - 1], varList[j]);
                sortedOK = false;
            }
        }
    }
}

void test()
{
    //case counter
    int testCase = 0;
    //sort function object
    auto sortFunc = BubbleSort;
    //show case result lambda function
    auto showFunc = [&testCase](const char* caseDescription){cout << "case[" << testCase++ << "]\t(" << caseDescription << ") \t\tok " << endl; };

    cout << "test begin : " << endl << endl;

    //case empty list
    {
        sortFunc(nullptr, 0);
        showFunc("case empty list");
    }
    //case wrong size
    {
        int nTestList[] = { 13, 52, 32, 15, 66, 2, 99, 202, 103, 2 };
        sortFunc(nTestList, 0);
        showFunc("case wrong size");
    }
    //case size == 1
    {
        int var = 13;
        int varList[] = { var };
        sortFunc(varList, 1);
        assert(var == varList[0]);
        showFunc("case size == 1");
    }
    //case normal sort
    {
        int varList[] = { 13, 52, 32, 15, 66, 2, 99, 202, 103, 2 };
        const int size = sizeof(varList) / sizeof(int);
        const int resultList[] = { 2, 2, 13, 15, 32, 52, 66, 99, 103, 202 };
        static_assert(sizeof(varList) == sizeof(resultList),"size of varList is not equal with resultList!!");

        sortFunc(varList, size);
        for (int i = 0; i < size; i++){ assert(varList[i] == resultList[i]); }
        showFunc("case normal sort");
    }
    //case sorted list
    {
        int varList[] = { 2, 2, 13, 15, 32, 52, 66, 99, 103, 202 };
        const int size = sizeof(varList) / sizeof(int);
        const int resultList[] = { 2, 2, 13, 15, 32, 52, 66, 99, 103, 202 };
        static_assert(sizeof(varList) == sizeof(resultList), "size of varList is not equal with resultList!!");

        sortFunc(varList, size);
        for (int i = 0; i < size; i++){ assert(varList[i] == resultList[i]); }
        showFunc("case sorted list");
    }
    cout << endl << "test done ! " << endl << endl;
}
int main(int argc, char* argv[])
{
    test();
    return 0;
}
C++11写算法之冒泡排序

C++11写算法之冒泡排序,布布扣,bubuko.com

C++11写算法之冒泡排序

上一篇:Python: 设计模式 之 工厂模式例(2)(神奇的Python)


下一篇:linux多线程编程(转)