有序環形數列的查找問題

問題:有一個有序的環形數列,從小到大排好了,好比4, 5, 6, 1, 2, 3,從第四個位置開始當成環形看,就是一個有序數列1, 2, 3, 4, 5, 6。問題是在這個數列重找到給定的關鍵字。數組

看到有序,天然想到binary search。這個問題能夠用binary search作,每次二分,把數組分紅兩部分,一部分是普通的有序數列,一部分是原問題。spa

代碼以下:code

bool search(int arr[], int b, int e, int k)
{
    if (!arr || b < e || b < 0)
        return false;

    int s = b + (e - b)/2;
    if (arr[s] == k)
        return true;
    else if (arr[s] > k)
    {
        if (arr[s] > arr[b])
        {
             if (k >= arr[b])
                return bsearch(arr, b, s-1, k);
            else
                return search(arr, s+1, e, k);
        }
        else
        {
            return search(arr, b, s-1, k);
        }
    }
    else
    {
        if (arr[s] > arr[b])
            return bsearch(arr, s+1, e, k);
        else
        {
            if (k >= arr[b])
                return search(arr, e, s-1, k);
            else
                return bsearch(arr, s+1, e, k);
        }
}
相關文章
相關標籤/搜索