Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

searching a element in a array which is rotated N times

Tags:

algorithm

I have a sorted array which is rotated n times, n is unknown.Now I want to search an element using binary search in O(nlog n).I implemented the following code, it works fine. But I think condition if((end-start)==1 ) can be skipped by making some modifications, can any one suggest?

Eg of array 1 2 3 4 5 
            2 3 4 5 1 //rotated once

Code:

public static int srch(int a[],int start,int end,int key){
    if(start>end)
        return -1;

    if((end-start)==1 ){
        if(key==a[start])
            return start;
        else if(key==a[end])
            return end;
        else
            return -1;
    }
    int mid = (start+end)/2;

    if(a[mid]== key){
        return mid;
    }
    else{
        if(a[start] < a[mid] ){
            //first half is sorted
            if(key>a[mid]|| key <a[start]){
                start= mid+1;
            }else{
                end =mid-1;
            }
        }else{
            //second half is sorted

            if(key>a[mid]){
                start= mid+1;
            }else{
                end =mid-1;
            }
        }
        return srch(a, start, end, key);
    }
}

Any better/simple/more efficient solution?

like image 362
dojoBeginner Avatar asked Jan 29 '26 00:01

dojoBeginner


1 Answers

Your solution fails for array {4,5,1,2,3} and key=4. I think a modification in second part will solve the problem

else{
            //second half is sorted

            if(key>a[mid] && key<=a[end]){// modified condition
                start= mid+1;
            }else{
                end =mid-1;
            }

But I think condition if((end-start)==1 ) can be skipped by making some modifications, can any one suggest?

I suppose this condition is not required at all. Can u suggest a test case which fails for your modified code.

public static int srch(int a[],int start,int end,int key){
    if(start>end)
        return -1;

     int mid = (start+end)/2;

    if(a[mid]== key){
        return mid;
    }
    else{
        if(a[start] < a[mid] ){
            //first half is sorted
            if(key>a[mid]|| key <a[start]){
                start= mid+1;
            }else{
                end =mid-1;
            }
        }else{
            //second half is sorted

            if(key>a[mid] && key<=a[high]){
                start= mid+1;
            }else{
                end =mid-1;
            }
        }
        return srch(a, start, end, key);
    }
}
like image 123
Terminal Avatar answered Jan 31 '26 07:01

Terminal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!