Search an element in a reverse sorted array

07 May, 2021
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 = 4Output: 1Explanation: Element X (= 4) is present at index 1.Therefore, the required output is 1.
Input: arr[] = {10, 8, 2, -9}, X = 5Output: -1Explanation: 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 [mid + 1, end]. So search for X in the subarray {arr[mid + 1], .., arr[end]} .Otherwise, search in the subarray {arr[start], ...., arr[mid]}
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 [mid + 1, end]. So search for X in the subarray {arr[mid + 1], .., arr[end]} .
Otherwise, search in the subarray {arr[start], ...., arr[mid]}
Below is the implementation of the above approach:
C
C++
Java
Python3
C#
Javascript
// C program for the above approach#include <stdio.h> // Function to search if element X// is present in reverse sorted arrayint 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 Codeint 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
// 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 arrayint 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 Codeint 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;}
// Java Program to implement// the above approachclass 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 program to implement# the above approach # Function to search if element X# is present in reverse sorted arraydef 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 Codeif __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# Program to implement// the above approachusing System;class GFG{ // Function to search if element X// is present in reverse sorted arraystatic 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 codepublic 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
<script>// JavaScript program to implement// the above approach // Function to search if element X// is present in reverse sorted arrayfunction 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>
1
 
Time Complexity: O(log2N)Auxiliary Space: O(1)
mohit kumar 29
princi singh
pradeepmondalp
surbhityagi15
array-traversal-question
Binary Search
Arrays
Searching
Sorting
Arrays
Searching
Sorting
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Binary Search
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
Find the Missing Number