C++11写算法之顺序查找

从这篇博文起,将尝试使用C++11来写常用算法与数据结构。

本篇博文以最简单的顺序查找作为系列博文的起点,并作约定如下:

1,变量名 : varList ; 函数名 : SequentialFind ;

2,尽量描写算法本身,因而均不含模板,数据类型均为int;

3,所有代码均在同一个cpp中;

4,代码均在 vs2013g++ 4.8.2 中编译通过;

5,g++编译命令:g++ -std=c++11 sequential_find.cpp 。

 

顺序查找没什么好说的,这里主要看看C++11的lambdaauto新语义。

时间复杂度:O(n)

空间复杂度:O(1)

show me the code !

// #if __cplusplus < 201103L 
// #error "must be compiled under c++11 support platform!!!"
// #endif
#include <iostream>
#include <algorithm>
#include <iterator>
#include <cassert>
using namespace std;

int SequentialFind(const int varList[], const int size, const int target)
{
    if (!varList || size < 0)
    {
        return -1;
    }
    int index = -1;
    for (int i = 0; i < size;i++)
    {
        if (varList[i] == target)
        {
            index = i;
            break;
        }
    }
    return index;
}

void test()
{
    //case counter
    int testCase = 0;
    //find function object
    auto findFunc = SequentialFind;
    //show case result lambda function
    auto showFunc = [&testCase](){cout << "case[" << testCase++ << "] ok... "<<endl; };

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

    //case empty list
    {
        assert(-1 == findFunc(nullptr, 0, 0));
        showFunc();
    }
    //case wrong list size
    {
        const int testList[] = { 11,5,7,9,3, 2, 3 ,4,1,-2};
        assert(-1 == findFunc(testList, 0, 0));
        showFunc();
    }
    //case not found
    {
        const int testList[] = { 11, 5, 7, 9, 3, 2, 3, 4, 1, -2 };
        const int size = sizeof(testList) / sizeof(int);
        const int target = -33;
        assert(-1 == findFunc(testList, 0, 0));
        showFunc();
    }
    //case found at begin position
    {
        const int testList[] = { 11, 5, 7, 9, 3, 2, 3, 4, 1, -2 };
        const int size = sizeof(testList) / sizeof(int);
        const int target = 11;
        assert(0 == findFunc(testList, size, target));
        showFunc();
    }
    //case found at random position
    {
        const int testList[] = { 11, 5, 7, 9, 3, 2, 3, 4, 1, -2 };
        const int size = sizeof(testList) / sizeof(int);
        const int target = 9;
        assert(3 == findFunc(testList, size, target));
        showFunc();
    }
    //case found at end position
    {
        const int testList[] = { 11, 5, 7, 9, 3, 2, 3, 4, 1, -2 };
        const int size = sizeof(testList) / sizeof(int);
        const int target = -2;
        assert(size - 1 == findFunc(testList, size, target));
        showFunc();
    }

    cout <<endl<< "test done ! " << endl << endl;
}

int main(int argc, char* argv[])
{
    test();
    return 0;
}
posted @ 2014-04-22 22:46  *神气*  阅读(1696)  评论(0编辑  收藏  举报