📜  搜索反向排序数组中的元素

📅  最后修改于: 2021-04-29 14:13:59             🧑  作者: Mango

给定一个以递减顺序排序的数组arr []和一个整数X ,任务是检查给定数组中是否存在X。如果数组中存在X ,则打印其索引(基于0的索引)。否则,打印-1

例子:

天真的方法:解决问题的最简单方法是遍历数组,对于每个元素,检查其是否等于X。如果发现任何满足该条件的元素,则打印该元素的索引。否则打印-1

时间复杂度: O(N)
辅助空间: O(1)

高效方法:要解决此问题,其想法是根据本文中讨论的方法使用二进制搜索来搜索排序数组中的元素。请按照以下步骤解决问题:

  1. X与中间元素进行比较。
  2. 如果X与中间元素( arr [mid] )相匹配,则返回索引mid
  3. 如果发现X大于arr [mid] ,则X只能位于子数组[mid +1,end]中。因此,在子数组{arr [mid + 1],..,arr [end]}中搜索X。
  4. 否则,在子数组{arr [start],…。,arr [mid]}中搜索

下面是上述方法的实现:

C
// C program for the above approach
#include 
 
// 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


C++
// C++ program to implement
// the above approach
 
#include 
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;
}


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


输出:
1

时间复杂度: O(log 2 N)
辅助空间: O(1)