📌  相关文章
📜  在通过从随机索引反转子数组形成的排序数组中搜索元素

📅  最后修改于: 2021-10-26 06:46:33             🧑  作者: Mango

给定一个大小为N的排序数组arr[]和一个整数键,任务是找到数组中存在的索引。给定的阵列已经通过反转子阵列获得{ARR [0],ARR [R]}{ARR [R + 1],ARR [N – 1]}在一些随机指数R.如果该不存在于数组,打印-1

例子:

朴素方法:解决问题的最简单方法是遍历数组并检查数组中是否存在。如果找到,则打印索引。否则,打印-1。

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

高效的方法:为了优化上述方法,其思想是对数组应用修改后的二分搜索来查找key 。请按照以下步骤解决此问题:

  • l初始化为0 ,将h初始化为N – 1,以存储用于二分搜索的搜索空间的边界元素的索引。
  • l小于或等于h 时迭代
    • 将中间值存储在一个变量中, mid(l+h)/2
    • 如果arr[mid]等于key 然后打印mid作为答案并返回。
    • 如果arr[l]大于或等于arr[mid] 这意味着随机索引位于mid的右侧。
      • 如果key的值介于arr[mid]arr[l] 之间,则将h更新为mid-1
      • 否则,将l更新为mid+1。
    • 否则,这意味着随机点位于mid的左侧。
    • 如果key的值在arr[h]arr[mid]之间,更新lmid+1。
    • 否则,将h更新为mid-1
  • 最后,如果未找到密钥,则打印-1

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to search an element in a
// sorted array formed by reversing
// subarrays from a random index
int find(vector arr, int N, int key)
{
     
    // Set the boundaries
    // for binary search
    int l = 0;
    int h = N - 1;
 
    // Apply binary search
    while (l <= h)
    {
         
        // Initialize the middle element
        int mid = (l + h) / 2;
 
        // If element found
        if (arr[mid] == key)
            return mid;
 
        // Random point is on
        // right side of mid
        if (arr[l] >= arr[mid])
        {
             
            // From l to mid arr
            // is reverse sorted
            if (arr[l] >= key && key >= arr[mid])
                h = mid - 1;
            else
                l = mid + 1;
        }
         
        // Random point is on
        // the left side of mid
        else
        {
             
            // From mid to h arr
            // is reverse sorted
            if (arr[mid] >= key && key >= arr[h])
                l = mid + 1;
            else
                h = mid - 1;
        }
    }
     
    // Return Not Found
    return -1;
}
 
// Driver Code
int main()
{
     
    // Given Input
    vector arr = { 10, 8, 6, 5, 2, 1, 13, 12 };
     
    int N = arr.size();
    int key = 8;
     
    // Function Call
    int ans = find(arr, N, key);
     
    cout << ans;
}
 
// This code is contributed by mohit kumar 29


Java
// Java program for the above approach
import java.util.*;
public class GFG {
 
// Function to search an element in a
// sorted array formed by reversing
// subarrays from a random index
public static int find(Vector arr, int N, int key)
{
     
    // Set the boundaries
    // for binary search
    int l = 0;
    int h = N - 1;
 
    // Apply binary search
    while (l <= h)
    {
         
        // Initialize the middle element
        int mid = (l + h) / 2;
 
        // If element found
        if (arr.get(mid) == key)
            return mid;
 
        // Random point is on
        // right side of mid
        if (arr.get(l) >= arr.get(mid))
        {
             
            // From l to mid arr
            // is reverse sorted
            if (arr.get(l) >= key && key >= arr.get(mid))
                h = mid - 1;
            else
                l = mid + 1;
        }
         
        // Random point is on
        // the left side of mid
        else
        {
             
            // From mid to h arr
            // is reverse sorted
            if (arr.get(mid) >= key && key >= arr.get(h))
                l = mid + 1;
            else
                h = mid - 1;
        }
    }
     
    // Return Not Found
    return -1;
}
 
 
// Drive Code
public static void main(String args[])
{
   Vector arr = new Vector ();
   arr.add(10);
   arr.add(8);
   arr.add(6);
   arr.add(5);
   arr.add(2);
   arr.add(1);
   arr.add(13);
   arr.add(12);
    int N = arr.size();
    int key = 8;
     
    // Function Call
    int ans = find(arr, N, key);
     
      System.out.println( ans);
}
 
}
 
//This code is contributed by SoumikMondal


Python3
# Python program for the above approach
 
# Function to search an element in a
# sorted array formed by reversing
# subarrays from a random index
def find(arr, N, key):
   
    # Set the boundaries
    # for binary search
    l = 0
    h = N-1
 
    # Apply binary search
    while l <= h:
       
          # Initialize the middle element
        mid = (l+h)//2
 
        # If element found
        if arr[mid] == key:
            return mid
 
        # Random point is on
        # right side of mid
        if arr[l] >= arr[mid]:
 
            # From l to mid arr
            # is reverse sorted
            if arr[l] >= key >= arr[mid]:
                h = mid-1
            else:
                l = mid+1
 
        # Random point is on
        # the left side of mid
        else:
 
            # From mid to h arr
            # is reverse sorted
            if arr[mid] >= key >= arr[h]:
                l = mid+1
            else:
                h = mid-1
 
    # Return Not Found
    return -1
 
 
# Driver Code
if __name__ == "__main__":
 
    # Given Input
    arr = [10, 8, 6, 5, 2, 1, 13, 12]
    N = len(arr)
    key = 8
 
    # Function Call
    ans = find(arr, N, key)
    print(ans)


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to search an element in a
// sorted array formed by reversing
// subarrays from a random index
static int find(List arr, int N, int key)
{
     
    // Set the boundaries
    // for binary search
    int l = 0;
    int h = N - 1;
 
    // Apply binary search
    while (l <= h)
    {
         
        // Initialize the middle element
        int mid = (l + h) / 2;
 
        // If element found
        if (arr[mid] == key)
            return mid;
 
        // Random point is on
        // right side of mid
        if (arr[l] >= arr[mid])
        {
             
            // From l to mid arr
            // is reverse sorted
            if (arr[l] >= key && key >= arr[mid])
                h = mid - 1;
            else
                l = mid + 1;
        }
         
        // Random point is on
        // the left side of mid
        else
        {
             
            // From mid to h arr
            // is reverse sorted
            if (arr[mid] >= key && key >= arr[h])
                l = mid + 1;
            else
                h = mid - 1;
        }
    }
     
    // Return Not Found
    return -1;
}
 
// Driver Code
public static void Main()
{
     
    // Given Input
    List arr = new List(){ 10, 8, 6, 5,
                                     2, 1, 13, 12 };
     
    int N = arr.Count;
    int key = 8;
     
    // Function Call
    int ans = find(arr, N, key);
     
    Console.Write(ans);
}
}
 
// This code is contributed by ipg2016107


Javascript


输出:
1

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程