Find Minimum 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).

Find the minimum element.

You may assume no duplicate exists in the array.

二分法来实现分半查找

 

  1. int findMin(vector<int> &num) {
  2. int n_size = num.size();
  3. if(n_size == 0) return 0;
  4. if(n_size == 1) return num[0];
  5. int start = 0;
  6. int end = n_size-1;
  7. while(num[start] > num[end]) {
  8. if(end - start == 1) {
  9. return num[end];
  10. }
  11. int mid = start + ((end-start)>>1);
  12. if(num[mid] > num[end]) {
  13. start = mid;
  14. } else {
  15. end = mid;
  16. }
  17. }
  18. return num[start];
  19. }
posted @ 2014-12-16 15:05  purejade  阅读(89)  评论(0)    收藏  举报