首页 > 代码库 > 查找算法

查找算法

线性查找(Linear Search):

时间复杂度:O(n)

int linerSearch(int * array, int n, int x)
{
    for (int i = 0; i < n; i++)
    {
        if (array[i] == x)
            return i;
    }

    return -1;
}

 


二分查找(Binary Search):

/* recursive version */
int binarySearch(int *array, int l, int r, int x)
{
    if (l <= r)
    {
        int m = (l + r) / 2;

        if (array[m] == x)
            return m;
        else if (array[m] > x)
            return binarySearch(array, l, m - 1, x);
        else
            return binarySearch(array, m + 1, r, x);
    }

    return -1;
}

/* iteration version */
int binarySearch(int *array, int l, int r, int x)
{
    int m;
    while (l <= r)
    {
        m = (l + r) / 2;

        if (array[m] == x)
            return m;
        else if (array[m] > x)
            r = m - 1;
        else
            l = m + 1;
    }

    return -1;
}

 

查找算法