Suppose a sorted array is rotated on some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2 ).
You is given a target value to search. If found in the array is return its index, otherwise return-1.
Assume no duplicate exists in the array.
Idea: Two-point search, remove half of the error options at a time.
Note that every time L = m + 1, r = m-1 prevents infinite loops.
intSearchintA[],intNinttarget) { intL =0, R = N-1; while(L <=r)//note that there is an equal sign {intm = (L + r)/2; if(A[m] = =target)returnm; if(A[l] <= a[m] && a[m] <= A[r])//Order of { if(A[m] >target) R= M-1; ElseL= m +1; } Else if(A[l] >= a[m] && a[m] <= A[r])//the beginning goes to the left half. { if(A[m] < target && target <= A[r])//in the right-hand partL = m +1; ElseR= M-1; } Else //the beginning goes to the right half. { if(A[l] <= target && target <= a[m])//in the left half partr = M-1; ElseL= m +1; } } return-1;}
Great God simplified version: the idea of removing half of the options is different
intSearchintA[],intNinttarget) { intLo =0; intHi = N-1; while(Lo <=hi) { intMid = (lo + hi)/2; if(A[mid] = = target)returnmid; if(A[lo] <=A[mid]) { if(Target >= A[lo] && Target <A[mid]) {Hi= Mid-1; } Else{lo= Mid +1; } } Else { if(Target > A[mid] && target <=A[hi]) {Lo= Mid +1; } Else{Hi= Mid-1; } } } return-1;}
"Leetcode" Search in rotated Sorted Array (hard)