Search in rotated Sorted Array

Source: Internet
Author: User

Search in rotated Sorted Array

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.

The main idea of this problem: first find pivot, find the front of the pivot process has been found, just to the back of the two points to find can

1  Public classSolution {2      Public intSearchint[] A,inttarget) {3         inti = 0;4          for(; i < a.length; i++){5             if(i > 0 && a[i-1] > A[i])//find out where the axes are6                  Break;7             if(A[i] = =target)8                 returni;9         }Ten         if(i = = a.length)//not found One             return-1; A         //from the position of the axis to the last two points find starting from the position of I to length-1 -         intLow =i; -         intHigh = A.length-1; the         intMiddle; -          while(Low <=High ) { -Middle = (low + high)/2; -             if(A[middle] = =target) +                 returnMiddle; -             Else if(A[middle] > target) {//first half of the section to find +High = Middle-1; A}Else{//Second half of the section to find atLow = middle + 1; -             } -         } -          -         return-1; -     } in}

Search in rotated Sorted Array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.