算法9:在一个循环有序的数组里查找一个数

解题思路

采用中分方法进行查找,考虑到是循环有序的数组,存在一边有序的情况,将中间值与最左边值比较,查看是否有序,则左有序,否则就是右有序。然后再确定待查找值的区域。

c++代码

//loopBuffer:循环有序数组
//length:循环有序数组长度
//value:待查找的数
//return:返回待查找数在数组中的位置
int BinarySearch(int* loopBuffer,int length, int value)
{
    if(loopBuffer == NULL || length == 0)
    {
        cout<<"buffer is error"<<endl;
        return -1;
    }
    int left = 0;
    int right = length -1;
    int mid = (left+right)/2;

    while(left <= right)
    {
        mid = (left+right)/2;
        if(value == loopBuffer[mid])
        {
            return mid;
        }

        if(loopBuffer[left]<loopBuffer[mid])//左有序
        {
            if(loopBuffer[left]<= value && value <= loopBuffer[mid])
            {
                right = mid - 1;
            }
            else
            {
                left = mid +1;
            }
        }
        else //右有序
        {
            if(loopBuffer[mid] <= value && value <= loopBuffer[right])
            {
                left = mid+1;
            }
            else
            {
                right = mid-1;
            }
        }
    }

    return -1;
}

测试代码

int _tmain(int argc, _TCHAR* argv[])
{
    int loopBuffer[10] = {6,7,8,9,0,1,2,3,4,5};
    int i = 0;
    int value = 0;
    while(i < 10)
    {
        cout<<"please input a value in {6,7,8,9,0,1,2,3,4,5}:"<<endl;
        cin>>value;
        cout<<"pos = "<<BinarySearch(loopBuffer,10,value)<<endl;
        i++;
    }

    cout<<"please input a value not in {6,7,8,9,0,1,2,3,4,5}:"<<endl;
    cin>>value;
    cout<<"pos = "<<BinarySearch(loopBuffer,10,value)<<endl;
    return 0;
}
    原文作者:查找算法
    原文地址: https://blog.csdn.net/pplin/article/details/60954930
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞