Search in rotated sorted Array

Source: Internet
Author: User

Suppose a sorted array is rotated at some unknown to you beforehand.

(I. e .,0 1 2 4 5 6 7Might become4 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.

public class Solution {public int search(int[] A, int target) {int l = 0;int r = A.length-1;while (l <= r) {int mid = (l + r) / 2;if (A[mid] == target) {return mid;}if (A[mid] >= A[l]) {if (A[mid] > target && A[l] <= target) {r = mid - 1;} else {l = mid + 1;}} else {if (A[mid] < target && A[r] >= target) {l = mid + 1;} else {r = mid - 1;}}}return -1;}}





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.