Search an element in a reverse sorted array
Last Updated :
29 Mar, 2024
Given an array arr[] sorted in decreasing order, and an integer X, the task is to check if X is present in the given array or not. If X is present in the array, print its index ( 0-based indexing). Otherwise, print -1.
Examples:
Input: arr[] = {5, 4, 3, 2, 1}, X = 4
Output: 1
Explanation: Element X (= 4) is present at index 1.
Therefore, the required output is 1.
Input: arr[] = {10, 8, 2, -9}, X = 5
Output: -1
Explanation: Element X (= 5) is not present in the array.
Therefore, the required output is -1.
Naive Approach: The simplest approach to solve the problem is to traverse the array and for each element, check if it is equal to X or not. If any element is found to satisfy that condition, print the index of that element. Otherwise print -1.
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach: To solve the problem, the idea is to use Binary Search based on the approach discussed in the article search an element in a sorted array. Follow the steps below to solve the problem:
- Compare X with the middle element.
- If X matches with the middle element (arr[mid]), return the index mid.
- If X is found to be greater than the arr[mid], then X can only lie in the subarray [start, mid-1]. So search for X in the subarray {arr[start], .., arr[mid-1]} .
- Otherwise, search in the subarray {arr[mid+1], ...., arr[end]}
Below is the implementation of the above approach:
C++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to search if element X
// is present in reverse sorted array
int binarySearch(int arr[], int N, int X)
{
// Store the first index of the
// subarray in which X lies
int start = 0;
// Store the last index of the
// subarray in which X lies
int end = N;
while (start <= end) {
// Store the middle index
// of the subarray
int mid = start
+ (end - start) / 2;
// Check if value at middle index
// of the subarray equal to X
if (X == arr[mid]) {
// Element is found
return mid;
}
// If X is smaller than the value
// at middle index of the subarray
else if (X < arr[mid]) {
// Search in right
// half of subarray
start = mid + 1;
}
else {
// Search in left
// half of subarray
end = mid - 1;
}
}
// If X not found
return -1;
}
// Driver Code
int main()
{
int arr[] = { 5, 4, 3, 2, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
int X = 5;
cout << binarySearch(arr, N, X);
return 0;
}
C
// C program for the above approach
#include <stdio.h>
// Function to search if element X
// is present in reverse sorted array
int binarySearch(int arr[], int N, int X)
{
// Store the first index of the
// subarray in which X lies
int start = 0;
// Store the last index of the
// subarray in which X lies
int end = N;
while (start <= end) {
// Store the middle index
// of the subarray
int mid = start
+ (end - start) / 2;
// Check if value at middle index
// of the subarray equal to X
if (X == arr[mid]) {
// Element is found
return mid;
}
// If X is smaller than the value
// at middle index of the subarray
else if (X < arr[mid]) {
// Search in right
// half of subarray
start = mid + 1;
}
else {
// Search in left
// half of subarray
end = mid - 1;
}
}
// If X not found
return -1;
}
// Driver Code
int main()
{
int arr[] = { 5, 4, 3, 2, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
int X = 4;
int res = binarySearch(arr, N, X);
printf(" %d " , res);
return 0;
}
//This code is contributed by Pradeep Mondal P
Java
// Java Program to implement
// the above approach
class GFG {
// Function to search if element X
// is present in reverse sorted array
static int binarySearch(int arr[],
int N, int X)
{
// Store the first index of the
// subarray in which X lies
int start = 0;
// Store the last index of the
// subarray in which X lies
int end = N;
while (start <= end) {
// Store the middle index
// of the subarray
int mid = start
+ (end - start) / 2;
// Check if value at middle index
// of the subarray equal to X
if (X == arr[mid]) {
// Element is found
return mid;
}
// If X is smaller than the value
// at middle index of the subarray
else if (X < arr[mid]) {
// Search in right
// half of subarray
start = mid + 1;
}
else {
// Search in left
// half of subarray
end = mid - 1;
}
}
// If X not found
return -1;
}
public static void main(String[] args)
{
int arr[] = { 5, 4, 3, 2, 1 };
int N = arr.length;
int X = 5;
System.out.println(
binarySearch(arr, N, X));
}
}
Python3
# Python3 program to implement
# the above approach
# Function to search if element X
# is present in reverse sorted array
def binarySearch(arr, N, X):
# Store the first index of the
# subarray in which X lies
start = 0
# Store the last index of the
# subarray in which X lies
end = N
while (start <= end):
# Store the middle index
# of the subarray
mid = start + (end - start) // 2
# Check if value at middle index
# of the subarray equal to X
if (X == arr[mid]):
# Element is found
return mid
# If X is smaller than the value
# at middle index of the subarray
elif (X < arr[mid]):
# Search in right
# half of subarray
start = mid + 1
else:
# Search in left
# half of subarray
end = mid - 1
# If X not found
return -1
# Driver Code
if __name__ == '__main__':
arr = [ 5, 4, 3, 2, 1 ]
N = len(arr)
X = 5
print(binarySearch(arr, N, X))
# This code is contributed by mohit kumar 29
C#
// C# Program to implement
// the above approach
using System;
class GFG{
// Function to search if element X
// is present in reverse sorted array
static int binarySearch(int []arr,
int N, int X)
{
// Store the first index of the
// subarray in which X lies
int start = 0;
// Store the last index of the
// subarray in which X lies
int end = N;
while (start <= end)
{
// Store the middle index
// of the subarray
int mid = start +
(end - start) / 2;
// Check if value at middle index
// of the subarray equal to X
if (X == arr[mid])
{
// Element is found
return mid;
}
// If X is smaller than the value
// at middle index of the subarray
else if (X < arr[mid])
{
// Search in right
// half of subarray
start = mid + 1;
}
else
{
// Search in left
// half of subarray
end = mid - 1;
}
}
// If X not found
return -1;
}
// Driver code
public static void Main(String[] args)
{
int []arr = {5, 4, 3, 2, 1};
int N = arr.Length;
int X = 5;
Console.WriteLine(binarySearch(arr, N, X));
}
}
// This code is contributed by Princi Singh
JavaScript
<script>
// JavaScript program to implement
// the above approach
// Function to search if element X
// is present in reverse sorted array
function binarySearch(arr, N, X)
{
// Store the first index of the
// subarray in which X lies
let start = 0;
// Store the last index of the
// subarray in which X lies
let end = N;
while (start <= end) {
// Store the middle index
// of the subarray
let mid = Math.floor(start
+ (end - start) / 2);
// Check if value at middle index
// of the subarray equal to X
if (X == arr[mid]) {
// Element is found
return mid;
}
// If X is smaller than the value
// at middle index of the subarray
else if (X < arr[mid]) {
// Search in right
// half of subarray
start = mid + 1;
}
else {
// Search in left
// half of subarray
end = mid - 1;
}
}
// If X not found
return -1;
}
// Driver Code
let arr = [ 5, 4, 3, 2, 1 ];
let N = arr.length;
let X = 5;
document.write(binarySearch(arr, N, X));
// This code is contributed by Surbhi Tyagi.
</script>
Time Complexity: O(log2N)
Auxiliary Space: O(1)
Similar Reads
Search in an almost sorted array Given a sorted integer array arr[] consisting of distinct elements, where some elements of the array are moved to either of the adjacent positions, i.e. arr[i] may be present at arr[i-1] or arr[i+1].Given an integer target. You have to return the index ( 0-based ) of the target in the array. If targ
7 min read
Search, Insert, and Delete in an Sorted Array | Array Operations How to Search in a Sorted Array?In a sorted array, the search operation can be performed by using binary search.Below is the implementation of the above approach:C++// C++ program to implement binary search in sorted array #include <bits/stdc++.h> using namespace std; int binarySearch(int arr[
15+ min read
Search an element in a sorted and rotated array with duplicates Given a sorted and rotated array arr[] and a key, the task is to find whether key exists in the rotated array (with duplicates).Examples: Input: arr[] = [3, 3, 3, 1, 2, 3], key = 3 Output: trueExplanation: arr[0] = 3Input: arr[] = {3, 3, 3, 1, 2, 3}, key = 11 Output: falseExplanation: 11 is not pres
6 min read
Search, Insert, and Delete in an Unsorted Array | Array Operations In this post, a program to search, insert, and delete operations in an unsorted array is discussed.Search Operation:In an unsorted array, the search operation can be performed by linear traversal from the first element to the last element. Coding implementation of the search operation:C++// C++ prog
15+ min read
Searching Elements in an Array | Array Operations In this post, we will look into search operation in an Array, i.e., how to search an element in an Array, such as: Searching in an Unsorted Array using Linear SearchSearching in a Sorted Array using Linear SearchSearching in a Sorted Array using Binary SearchSearching in an Sorted Array using Fibona
15+ min read