
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Search in Rotated Sorted Array in Python
Consider we have an array sorted in ascending order, and that is rotated at some pivot unknown to you beforehand. For example, [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]. We have given a target value to the search. If we can get it in the array, then return its index, otherwise return -1. We can assume no duplicate exists in the array. So if the array is like [4,5,6,7,0,1,2], then the output will be 4. as the index of this element is present at index 4.
To solve this, we will follow these steps −
- low := 0 and high := length of array
- while low < high
- find mid as mid := low + (high - low)/2
- if arr[mid] = target, then return mid
- if arr[low] <= arr[mid]
- if target >= arr[low] and target < arr[mid], then high := mid, otherwise low := mid + 1
- otherwise
- if target <= arr[high - 1] and target > arr[mid], then low := mid + 1, otherwise high := mid
- return -1
Example(Python)
Let us see the following implementation to get better understanding −
class Solution(object): def search(self, nums, target): low = 0 high = len(nums) while low<high: mid = low + (high-low)//2 if nums[mid] == target: return mid if nums[low]<=nums[mid]: if target >=nums[low] and target <nums[mid]: high = mid else: low = mid+1 else: if target<=nums[high-1] and target>nums[mid]: low = mid+1 else: high = mid return -1 ob1 = Solution() print(ob1.search([4,5,6,7,8,0,1,2], 0))
Input
[4,5,6,7,0,1,2] 0
Output
5
- Related Articles
- Search in Rotated Sorted Array II in Python
- Search in Rotated Sorted Array II in C++
- C++ program to search an element in a sorted rotated array
- Check if an array is sorted and rotated in Python
- Find Minimum in Rotated Sorted Array in C++
- Find Minimum in Rotated Sorted Array II in C++
- Program to check whether an array Is sorted and rotated in Python
- Find the Rotation Count in Rotated Sorted array in C++
- Maximum element in a sorted and rotated array in C++
- Convert Sorted Array to Binary Search Tree in Python
- Check if an array is sorted and rotated in C++
- Finding smallest element in a sorted array which is rotated in JavaScript
- Search elements in a sorted object array in Java
- Search in a Sorted Array of Unknown Size in C++
- Count rotations in sorted and rotated linked list in C++

Advertisements