Search insert position of K in a sorted array - GeeksforGeeks

27 Apr, 2022
Given a sorted array arr[] consisting of N distinct integers and an integer K, the task is to find the index of K, if it’s present in the array arr[]. Otherwise, find the index where K must be inserted to keep the array sorted.
Examples: 
Input: arr[] = {1, 3, 5, 6}, K = 5Output: 2Explanation: Since 5 is found at index 2 as arr[2] = 5, the output is 2.
Input: arr[] = {1, 3, 5, 6}, K = 2Output: 1Explanation: Since 2 is not present in the array but can be inserted at index 1 to make the array sorted.
Naive Approach: Follow the steps below to solve the problem:
Iterate over every element of the array arr[] and search for integer K.
If any array element is found to be equal to K, then print index of K.
Otherwise, if any array element is found to be greater than K, print that index as the insert position of K. If no element is found to be exceeding K, K must be inserted after the last array element.
Below is the implementation of above approach :
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find insert position of Kint 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 Codeint 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 program for the above approachimport java.io.*; class GFG{ // Function to find insert position of Kstatic 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 Codepublic 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
# Python program for the above approach # Function to find insert position of Kdef 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 Codearr = [1, 3, 5, 6]n = len(arr)K = 2print(find_index(arr, n, K))
// C# program for the above approachusing System; class GFG{ // Function to find insert position of Kstatic 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 Codepublic 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
<script> // Javascript program for the above approach // Function to find insert position of Kfunction find_index(arr, n, K){         // Traverse the array    for(let 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 codelet arr = [ 1, 3, 5, 6 ];let n = arr.length;let K = 2;  document.write(find_index(arr, n, K)); // This code is contributed by splevel62   </script>
1
 
Time Complexity: O(N)Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use Binary Search. Follow the steps below to solve the problem: 
Set start and end as 0 and N – 1, where the start and end variables denote the lower and upper bound of the search space respectively.
Calculate mid = (start + end) / 2.
If arr[mid] is found to be equal to K, print mid as the required answer.
If arr[mid] exceeds K, set high = mid – 1 Otherwise, set  low = mid + 1. 
Below is the implementation of above approach :
C++
C
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find insert position of Kint 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 Codeint 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;} // This code is contributed by Aditya Kumar (adityakumar129)
// C program for the above approach #include<stdio.h> // Function to find insert position of Kint 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 Codeint main(){    int arr[] = { 1, 3, 5, 6 };    int n = sizeof(arr) / sizeof(arr[0]);    int K = 2;    printf("%d",find_index(arr, n, K));    return 0;} // This code is contributed by Aditya Kumar (adityakumar129)
// Java program for the above approachimport java.io.*; class GFG{ // Function to find insert position of Kstatic 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 Codepublic 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
# Python program to implement# the above approach # Function to find insert position of Kdef 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 Codearr = [1, 3, 5, 6]n = len(arr)K = 2print(find_index(arr, n, K))
// C# program for the above approachusing System; class GFG{ // Function to find insert position of Kstatic 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 Codepublic 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
<script>// JavaScript program for the above approach // Function to find insert position of Kfunction find_index(arr, n, K){    // Lower and upper bounds    let start = 0;    let end = n - 1;     // Traverse the search space    while (start <= end) {        let mid = Math.floor((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    let arr = [ 1, 3, 5, 6 ];    let n = arr.length;    let K = 2;    document.write(find_index(arr, n, K) + "<br>");    // This code is contributed by Surbhi Tyagi.</script>
1
 
Time Complexity: O(log N)Auxiliary Space: O(1)
akhilsaini
splevel62
surbhityagi15
adityakumar129
array-rearrange
array-traversal-question
Binary Search
Arrays
Searching
Arrays
Searching
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number