俊介三

一天更新一点,一天积累一点

导航

一个数组是由一个递减数列左移若干位形成的,比如 {4 , 3 , 2 , 1 , 6 , 5}
是由 {6 , 5 , 4 , 3 , 2 , 1} 左移两位形成的,在这种数组中查找某一个数。

思路:二分查找,用if语句来进行“加强条件限制”(相当于中学时候分段讨论的思想),把具有单调性的一半讨论出来,如果不在此单调性段内,则在复杂的else中找去。知道找到或最后找不到为止。

代码:

#include <stdio.h>

int helper(int* arr, int key, int start, int end);

//return the index of the element if exists, else return -1
int shiftedBinarySearch(int*arr, int len , int key){
    return helper(arr,key,0,len-1);
}

int helper(int* arr, int key, int start, int end){
    if(start>end) return -1;
    int mid = (start+end)/2;
    if(arr[mid]==key) return mid;
    if(arr[start]==key) return start;
    if(arr[end]==key) return end;
    if(arr[start]>arr[mid]){
        if(key<=arr[start] && key>arr[mid]) return helper(arr,key,start, mid-1);
        else return helper(arr,key,mid+1,end);
    }else{
        if(key>arr[mid] && key<=arr[end]) return helper(arr,key,mid+1,end);
        else return helper(arr,key,start, mid-1);
    }
}
    
int main(){
    int arr[] = {4,3,2,1,6,5};
    int i=3;
    for(i=1;i<7;i++)
        printf("%d\n",shiftedBinarySearch(arr,6,i));

    return 0;
}