ch9.3: binary search a number from a sorted & twisted array

Given a sorted array of n integers that has been rotated an unknown number of times, give an O(log n) algorithm that finds an element in the array. You may assume that the array was originally sorted in increasing order.

if(x<= a[low] && x>a[mid]) // must have = for low because the a[mid] cannot be equal but a[low] maybe
This code doesn't work for duplicate case.

#include <iostream>

int search(int a[], int low, int high, int x){
    while(low <= high){
        int mid = (low+high)>>1;
        if(x==a[mid]) return mid;
        if(a[low]> a[mid]){
            if(x<= a[low] && x>a[mid]) // must have = for low
                low = mid+1;
            else
                high = mid -1;
        }
        else{
            if(x<a[mid] && x>=a[low])  // must have = for low
                high = mid -1;
            else
                low = mid + 1;
        }    
    }
    return -1;
}


using namespace std;

int main()
{
   cout << "Hello World" << endl; 
   int a[12] = {
        15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14
    };
    int b[19] = {
        2,2,2,2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2
    };
    cout<<search(a, 0, 11, 4)<<endl;
    cout<<search(b, 0, 18, 3)<<endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值