# Question

Formatted question description: https://leetcode.ca/all/33.html

# 33. Search in Rotated Sorted Array

Medium

## Description

Suppose an array sorted in ascending order 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.

Your algorithm’s runtime complexity must be in the order of O(log n).

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0

Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3

Output: -1

## Solution

To solve the problem in O(log n) runtime complexity, use binary search. Since the sorted array is rotated at some pivot, the logic is a little different from traditional binary search.

Use two pointers low and high, which initially point to the begin and the end of the array respectively. The loop condition is low <= high. Each time choose mid as the average of low and high. If nums[mid] == target, then return mid. Otherwise, decide which half should be searched next, [low, mid - 1] or [mid + 1, high]. Two cases may exist. The first case is that nums[low] <= nums[mid], which means the rotation point is on the right of mid. Search in [low, mid - 1] if target is between nums[low] and nums[mid], and otherwise search in [mid + 1, high]. The first case is that nums[low] > nums[mid], which means the rotation pointer is on the left of mid. Search in [mid + 1, high] if target is between nums[mid] and nums[high], and otherwise search in [low, mid - 1]. If target is not found, return -1.

Java