The following program guide you to insert an element in a specific position in a given array.

To insert an element at a specific position, say k. First, we have to move all the elements starting from k, down by one position in order to accommodate the element at position of k.

The best possible case occurs when the element is to be inserted at last position. In this case, no element has to be moved.

The worst case occurs when the element is to be inserted at the first position. In this case, all the elements are moved down.

Therefore, the loop executes n times. Thus the complexity of the insertion operation is O(n) i.e linear time.

Java Code to insert an element at a specific position in Array

import java.util.Scanner;
public class Insert
{
    public static void main(String[] args)
    {
        int[] a = new int[50];
        Scanner obj = new Scanner(System.in);
        System.out.println("enter the size of an array");
        int size = obj.nextInt();
        System.out.println("enter the elements of the array");
        for(int i=0; i<size; i++)
        {
            a[i] = obj.nextInt();
        }
        System.out.println("ARRAY ELEMENTS BEFORE INSERTION");
        for(int i=0; i<size; i++)
        {
            System.out.println(a[i] + " ");
        }
        System.out.println("Enter the element that has to be inserted");
        int k = obj.nextInt();
        System.out.println("Enter the position where the element should be inserted");
        int pos = obj.nextInt();
        for(int i=size; i>pos; i--)
        {
            a[i] = a[i-1];
        }
        a[pos] = k;
        ++size;
        System.out.println("ARRAY ELEMENTS AFTER INSERTION");
        for(int i=0;i<size;i++)
        {
            System.out.println(a[i] + " ");
        }
    }
}

OUTPUT:

enter the size of an array
10
enter the elements of the array
1
2
3
4
5
6
7
8
9
10
ARRAY ELEMENTS BEFORE INSERTION
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
Enter the element that has to be inserted
0
Enter the position where the element should be inserted
1
ARRAY ELEMENTS AFTER INSERTION
1 
0 
2 
3 
4 
5 
6 
7 
8 
9 
10