📜  在排序数组中搜索K的插入位置

📅  最后修改于: 2021-05-17 18:12:43             🧑  作者: Mango

给定一个由N个不同的整数和一个整数K组成的排序数组arr [] ,任务是找到K的索引(如果它存在于数组arr []中) 。否则,找到必须在其中插入K的索引以保持数组排序。

例子:

天真的方法:请按照以下步骤解决问题:

  • 遍历数组arr []的每个元素,并搜索整数K。
  • 如果发现任何数组元素等于K ,则打印索引K。
  • 否则,如果发现任何数组元素大于K ,则将该索引打印为K的插入位置。如果没有发现超过K的元素,则必须在最后一个数组元素之后插入K。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find insert position of K
int find_index(int arr[], int n, int K)
{
    // Traverse the array
    for (int i = 0; i < n; i++)
 
        // If K is found
        if (arr[i] == K)
            return i;
 
        // If current array element
        // exceeds K
        else if (arr[i] > K)
            return i;
 
    // If all elements are smaller
    // than K
    return n;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 3, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
    cout << find_index(arr, n, K) << endl;
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
 
class GFG{
 
// Function to find insert position of K
static int find_index(int[] arr, int n, int K)
{
     
    // Traverse the array
    for(int i = 0; i < n; i++)
     
        // If K is found
        if (arr[i] == K)
            return i;
 
        // If current array element
        // exceeds K
        else if (arr[i] > K)
            return i;
 
    // If all elements are smaller
    // than K
    return n;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 3, 5, 6 };
    int n = arr.length;
    int K = 2;
     
    System.out.println(find_index(arr, n, K));
}
}
 
// This code is contributed by akhilsaini


Python3
# Python program for the above approach
 
# Function to find insert position of K
def find_index(arr, n, K):
     
    # Traverse the array
    for i in range(n):
         
        # If K is found
        if arr[i] == K:
            return i
             
        # If arr[i] exceeds K
        elif arr[i] > K:
            return i
             
    # If all array elements are smaller
    return n
 
# Driver Code
arr = [1, 3, 5, 6]
n = len(arr)
K = 2
print(find_index(arr, n, K))


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to find insert position of K
static int find_index(int[] arr, int n, int K)
{
     
    // Traverse the array
    for(int i = 0; i < n; i++)
     
        // If K is found
        if (arr[i] == K)
            return i;
 
        // If current array element
        // exceeds K
        else if (arr[i] > K)
            return i;
 
    // If all elements are smaller
    // than K
    return n;
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 1, 3, 5, 6 };
    int n = arr.Length;
    int K = 2;
     
    Console.WriteLine(find_index(arr, n, K));
}
}
 
// This code is contributed by akhilsaini


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find insert position of K
int find_index(int arr[], int n, int K)
{
    // Lower and upper bounds
    int start = 0;
    int end = n - 1;
 
    // Traverse the search space
    while (start <= end) {
        int mid = (start + end) / 2;
 
        // If K is found
        if (arr[mid] == K)
            return mid;
 
        else if (arr[mid] < K)
            start = mid + 1;
 
        else
            end = mid - 1;
    }
 
    // Return insert position
    return end + 1;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 3, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
    cout << find_index(arr, n, K) << endl;
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
 
class GFG{
 
// Function to find insert position of K
static int find_index(int[] arr, int n, int K)
{
     
    // Lower and upper bounds
    int start = 0;
    int end = n - 1;
 
    // Traverse the search space
    while (start <= end)
    {
        int mid = (start + end) / 2;
 
        // If K is found
        if (arr[mid] == K)
            return mid;
 
        else if (arr[mid] < K)
            start = mid + 1;
 
        else
            end = mid - 1;
    }
 
    // Return insert position
    return end + 1;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 3, 5, 6 };
    int n = arr.length;
    int K = 2;
     
    System.out.println(find_index(arr, n, K));
}
}
 
// This code is contributed by akhilsaini


Python3
# Python program to implement
# the above approach
 
# Function to find insert position of K
def find_index(arr, n, B):
 
    # Lower and upper bounds
    start = 0
    end = n - 1
 
    # Traverse the search space
    while start<= end:
 
        mid =(start + end)//2
 
        if arr[mid] == K:
            return mid
 
        elif arr[mid] < K:
            start = mid + 1
        else:
            end = mid-1
 
    # Return the insert position
    return end + 1
 
# Driver Code
arr = [1, 3, 5, 6]
n = len(arr)
K = 2
print(find_index(arr, n, K))


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to find insert position of K
static int find_index(int[] arr, int n, int K)
{
     
    // Lower and upper bounds
    int start = 0;
    int end = n - 1;
 
    // Traverse the search space
    while (start <= end)
    {
        int mid = (start + end) / 2;
 
        // If K is found
        if (arr[mid] == K)
            return mid;
 
        else if (arr[mid] < K)
            start = mid + 1;
 
        else
            end = mid - 1;
    }
 
    // Return insert position
    return end + 1;
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 1, 3, 5, 6 };
    int n = arr.Length;
    int K = 2;
     
    Console.WriteLine(find_index(arr, n, K));
}
}
 
// This code is contributed by akhilsaini


输出:
1



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

高效方法:为了优化上述方法,我们的想法是使用二进制搜索。请按照以下步骤解决问题:

  • startend设置为0N – 1 ,其中startend变量分别表示搜索空间的下限和上限。
  • 计算中=(开始+结束)/ 2
  • 如果发现arr [mid]等于K ,则将mid打印为所需答案。
  • 如果arr [mid]超过K ,则将low设置为mid + 1 。否则,将high设置为mid – 1

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find insert position of K
int find_index(int arr[], int n, int K)
{
    // Lower and upper bounds
    int start = 0;
    int end = n - 1;
 
    // Traverse the search space
    while (start <= end) {
        int mid = (start + end) / 2;
 
        // If K is found
        if (arr[mid] == K)
            return mid;
 
        else if (arr[mid] < K)
            start = mid + 1;
 
        else
            end = mid - 1;
    }
 
    // Return insert position
    return end + 1;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 3, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
    cout << find_index(arr, n, K) << endl;
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
 
class GFG{
 
// Function to find insert position of K
static int find_index(int[] arr, int n, int K)
{
     
    // Lower and upper bounds
    int start = 0;
    int end = n - 1;
 
    // Traverse the search space
    while (start <= end)
    {
        int mid = (start + end) / 2;
 
        // If K is found
        if (arr[mid] == K)
            return mid;
 
        else if (arr[mid] < K)
            start = mid + 1;
 
        else
            end = mid - 1;
    }
 
    // Return insert position
    return end + 1;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 3, 5, 6 };
    int n = arr.length;
    int K = 2;
     
    System.out.println(find_index(arr, n, K));
}
}
 
// This code is contributed by akhilsaini

Python3

# Python program to implement
# the above approach
 
# Function to find insert position of K
def find_index(arr, n, B):
 
    # Lower and upper bounds
    start = 0
    end = n - 1
 
    # Traverse the search space
    while start<= end:
 
        mid =(start + end)//2
 
        if arr[mid] == K:
            return mid
 
        elif arr[mid] < K:
            start = mid + 1
        else:
            end = mid-1
 
    # Return the insert position
    return end + 1
 
# Driver Code
arr = [1, 3, 5, 6]
n = len(arr)
K = 2
print(find_index(arr, n, K))

C#

// C# program for the above approach
using System;
 
class GFG{
 
// Function to find insert position of K
static int find_index(int[] arr, int n, int K)
{
     
    // Lower and upper bounds
    int start = 0;
    int end = n - 1;
 
    // Traverse the search space
    while (start <= end)
    {
        int mid = (start + end) / 2;
 
        // If K is found
        if (arr[mid] == K)
            return mid;
 
        else if (arr[mid] < K)
            start = mid + 1;
 
        else
            end = mid - 1;
    }
 
    // Return insert position
    return end + 1;
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 1, 3, 5, 6 };
    int n = arr.Length;
    int K = 2;
     
    Console.WriteLine(find_index(arr, n, K));
}
}
 
// This code is contributed by akhilsaini
输出:
1



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