Search in Rotated Sorted Array

Suppose a sorted array is rotated at 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 are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.

Solution: Binary search. O(lgn) eg. [4 5 6] -7- 8 1 2 3; 5 6 0 -1- [2 3 4]

 1 class Solution {
 2 public:
 3     int search(int A[], int n, int target) {
 4         int i = 0; 
 5         int j = n-1;
 6         while(i <= j) {
 7             int mid = i + (j-i)/2 ;
 8             if(A[mid] == target) return mid;
 9             if(A[i] <= A[mid]) {
10                 if(A[i] <= target && target < A[mid]) {
11                     j = mid - 1;
12                 }
13                 else {
14                     i = mid + 1;
15                 }
16             }
17             else {
18                 if(A[mid] < target && target <= A[j]) {
19                     i = mid + 1;
20                 }
21                 else {
22                     j = mid - 1;
23                 }
24             }
25         }
26         return -1;
27     }
28 };

 

posted @ 2014-03-14 21:40  beehard  阅读(101)  评论(0编辑  收藏  举报