PHP Program for Search an element in a sorted and rotated array
Last Updated :
22 Jul, 2024
An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time.

Example:Â
Input : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};
key = 3
Output : Found at index 8
Input : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};
key = 30
Output : Not found
Input : arr[] = {30, 40, 50, 10, 20}
key = 10
Output : Found at index 3
All solutions provided here assume that all elements in the array are distinct.
Basic Solution:Â
Approach:Â
- The idea is to find the pivot point, divide the array in two sub-arrays and perform binary search.
- The main idea for finding pivot is - for a sorted (in increasing order) and pivoted array, pivot element is the only element for which next element to it is smaller than it.
- Using the above statement and binary search pivot can be found.
- After the pivot is found out divide the array in two sub-arrays.
- Now the individual sub - arrays are sorted so the element can be searched using Binary Search.
Implementation:Â
Input arr[] = {3, 4, 5, 1, 2}
Element to Search = 1
1) Find out pivot point and divide the array in two
sub-arrays. (pivot = 2) /*Index of 5*/
2) Now call binary search for one of the two sub-arrays.
(a) If element is greater than 0th element then
search in left array
(b) Else Search in right array
(1 will go in else as 1 < 0th element(3))
3) If element is found in selected sub-array then return index
Else return -1.
Below is the implementation of the above approach:Â
PHP
<?php
// PHP Program to search an element
// in a sorted and pivoted array
// Standard Binary Search function
function binarySearch($arr, $low,
$high, $key)
{
if ($high < $low)
return -1;
/*low + (high - low)/2;*/
$mid = floor($low + $high) / 2;
if ($key == $arr[$mid])
return $mid;
if ($key > $arr[$mid])
return binarySearch($arr, ($mid + 1),
$high, $key);
else
return binarySearch($arr, $low,
($mid -1), $key);
}
// Function to get pivot.
// For array 3, 4, 5, 6, 1, 2
// it returns 3 (index of 6)
function findPivot($arr, $low, $high)
{
// base cases
if ($high < $low)
return -1;
if ($high == $low)
return $low;
/*low + (high - low)/2;*/
$mid = ($low + $high)/2;
if ($mid < $high and $arr[$mid] >
$arr[$mid + 1])
return $mid;
if ($mid > $low and $arr[$mid] <
$arr[$mid - 1])
return ($mid - 1);
if ($arr[$low] >= $arr[$mid])
return findPivot($arr, $low,
$mid - 1);
return findPivot($arr, $mid + 1, $high);
}
// Searches an element key
// in a pivoted sorted array
// arr[] of size n */
function pivotedBinarySearch($arr, $n, $key)
{
$pivot = findPivot($arr, 0, $n - 1);
// If we didn't find a pivot,
// then array is not rotated
// at all
if ($pivot == -1)
return binarySearch($arr, 0,
$n - 1, $key);
// If we found a pivot,
// then first compare
// with pivot and then
// search in two subarrays
// around pivot
if ($arr[$pivot] == $key)
return $pivot;
if ($arr[0] <= $key)
return binarySearch($arr, 0,
$pivot - 1, $key);
return binarySearch($arr, $pivot + 1,
$n - 1, $key);
}
// Driver Code
// Let us search 3
// in below array
$arr1 = array(5, 6, 7, 8, 9, 10, 1, 2, 3);
$n = count($arr1);
$key = 3;
// Function calling
echo "Index of the element is : ",
pivotedBinarySearch($arr1, $n, $key);
// This code is contributed by anuj_67.
?>
OutputIndex of the element is : 8
Complexity Analysis:Â
- Time Complexity: O(log n).Â
Binary Search requires log n comparisons to find the element. So time complexity is O(log n). - Space Complexity:O(1), No extra space is required.
Improved Solution:Â
Approach:
Instead of two or more pass of binary search the result can be found in one pass of binary search. The binary search needs to be modified to perform the search. The idea is to create a recursive function that takes l and r as range in input and the key.
1) Find middle point mid = (l + h)/2
2) If key is present at middle point, return mid.
3) Else If arr[l..mid] is sorted
a) If key to be searched lies in range from arr[l]
to arr[mid], recur for arr[l..mid].
b) Else recur for arr[mid+1..h]
4) Else (arr[mid+1..h] must be sorted)
a) If key to be searched lies in range from arr[mid+1]
to arr[h], recur for arr[mid+1..h].
b) Else recur for arr[l..mid]
Below is the implementation of above idea:Â
PHP
<?php
// Search an element in sorted and rotated
// array using single pass of Binary Search
// Returns index of key in arr[l..h] if
// key is present, otherwise returns -1
function search($arr, $l, $h, $key)
{
if ($l > $h) return -1;
$mid = ($l + $h) / 2;
if ($arr[$mid] == $key)
return $mid;
/* If arr[l...mid] is sorted */
if ($arr[$l] <= $arr[$mid])
{
/* As this subarray is
sorted, we can quickly
check if key lies in
half or other half */
if ($key >= $arr[$l] &&
$key <= $arr[$mid])
return search($arr, $l,
$mid - 1, $key);
return search($arr, $mid + 1,
$h, $key);
}
/* If arr[l..mid] is not
sorted, then arr[mid... r]
must be sorted*/
if ($key >= $arr[$mid] &&
$key <= $arr[$h])
return search($arr, $mid + 1,
$h, $key);
return search($arr, $l,
$mid-1, $key);
}
// Driver Code
$arr = array(4, 5, 6, 7, 8, 9, 1, 2, 3);
$n = sizeof($arr);
$key = 6;
$i = search($arr, 0, $n-1, $key);
if ($i != -1)
echo "Index: ", floor($i), "
";
else
echo "Key not found";
// This code is contributed by ajit
?>
Complexity Analysis:Â
- Time Complexity: O(log n).Â
Binary Search requires log n comparisons to find the element. So time complexity is O(log n). - Space Complexity: O(1).Â
As no extra space is required.
Thanks to Gaurav Ahirwar for suggesting above solution.Â
How to handle duplicates?Â
It doesn't look possible to search in O(Logn) time in all cases when duplicates are allowed. For example consider searching 0 in {2, 2, 2, 2, 2, 2, 2, 2, 0, 2} and {2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}.Â
It doesn’t look possible to decide whether to recur for the left half or right half by doing a constant number of comparisons at the middle.
Similar Articles:Â
Please refer complete article on Search an element in a sorted and rotated array for more details!
Similar Reads
PHP Program for Check if an array is sorted and rotated
Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated counter-clockwise. A sorted array is not considered as sorted and rotated, i.e., there should at least one rotation.Examples: Input : arr[] = { 3, 4, 5, 1, 2 }Output : YESThe above arra
3 min read
PHP Program for Ceiling in a sorted array
Given a sorted array and a value x, the ceiling of x is the smallest element in array greater than or equal to x, and the floor is the greatest element smaller than or equal to x. Assume than the array is sorted in non-decreasing order. Write efficient functions to find floor and ceiling of x. Examp
4 min read
PHP Program to Count 1's in a sorted binary array
Given a binary array sorted in non-increasing order, count the number of 1's in it. Examples: Input: arr[] = {1, 1, 0, 0, 0, 0, 0}Output: 2Input: arr[] = {1, 1, 1, 1, 1, 1, 1}Output: 7Input: arr[] = {0, 0, 0, 0, 0, 0, 0}Output: 0A simple solution is to linearly traverse the array. The time complexit
2 min read
PHP Program to Delete Middle Element from an Array
Given an array, the task is to delete the middle element of the array. If the array has an even number of elements, the middle element can be considered as the one closer to the start of the array (the lower middle).These are the following approaches:Table of ContentUsing array_splice() functionUsin
3 min read
PHP Program to Split Array and Add First Part to the End | Set 2
Given an array, the task is to split it from a specified position, and move the first part of array and add to the end. Examples: Input : Arr = [ 12, 10, 5, 6, 52, 36 ] k = 2 Output : Arr = [ 5, 6, 52, 36, 12, 10 ] Explanation : Split from index 2 and first part {12, 10} add to the end. Input : Arr
2 min read
PHP Program to Print all triplets in sorted array that form AP
Given a sorted array of distinct positive integers, print all triplets that form AP (or Arithmetic Progression)Examples : Input : arr[] = { 2, 6, 9, 12, 17, 22, 31, 32, 35, 42 };Output :6 9 122 12 2212 17 222 17 3212 22 329 22 352 22 4222 32 42Input : arr[] = { 3, 5, 6, 7, 8, 10, 12};Output :3 5 75
4 min read
PHP Program to Find Duplicate Elements from an Array
Given an array containing some repeated elements, the task is to find the duplicate elements from the given array. If array elements are not repeated, then it returns an empty array.Examples:Input: arr = [1, 2, 3, 6, 3, 6, 1]Output: [1, 3, 6]Input: arr = [3, 5, 2, 5, 3, 9]Output: [3, 5]There are two
6 min read
Remove Smallest and Largest Elements from PHP Array
In this article, we will learn how to remove the smallest and largest elements from an array in PHP. Handling arrays is a common task in PHP. We will cover various approaches to remove the smallest and largest elements from an array in PHP. Approach 1: Using sort() and array_shift()/array_pop() func
2 min read
PHP Program to Move All Zeroes to End of Array
Given an array of random numbers, Push all the zero's of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity i
3 min read
PHP Program for Range Queries for Frequencies of Array Elements
Given an array of n non-negative integers. The task is to find the frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type. Examples: Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};
2 min read