二分查找

二分查找序列必须基于已排序数组

二分查找的数组实现(c语言)

#include <stdio.h>

int Search(int * p,int n,int length) // n为查找的数字,length为数组长度
{
    if (length < 0 || p == NULL)
    {
        return -1;
    }

    int left = 0;
    int right = length - 1;

    while (left <= right)
    {
        int middle;
        middle = left + (right-left)/2;
        if (p[middle] < n)
        {
            left = middle + 1;
        }else if (p[middle] > n)
        {
             right = middle - 1;
        }
        else
        {
            return middle;
        }
    }

    return 0;
}


int main()
{
    int a[8] = {1,2,3,4,5,6,7,8};    //必须基于已排序数组
    int res = Search(a,4,8);
    printf("%d\n",res);

    return 0;
}

 

 

 

 

posted @ 2018-04-24 23:06  Chaz_Sun  阅读(131)  评论(0编辑  收藏  举报