Search an element in a reverse sorted array

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: 

  1. Compare X with the middle element.
  2. If X matches with the middle element (arr[mid]), return the index mid.
  3. 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]} .
  4. Otherwise, search in the subarray {arr[start], …., arr[mid]}

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 1;
        }
 
        // 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 1;
            }
 
            // 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));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 1
 
        # 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 1;
    }
 
    // 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

chevron_right


Output: 

1





 

Time Complexity: O(log2N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.