Java Program to Insert an Element in a Sorted Array

In the previous article, we have seen Java Program to Find the Number of Even and Odd Integers in an Array of Integers

In this article, we will learn how to enter an element in a sorted array by using Java programming language.

Java Program to Insert an Element in a Sorted Array

Prerequisite: 

See below articles to know more about Array, array declaration, array instantiation and array initialization.

In a sorted array initially, we will search for the position in which element should be inserted, then insert operation is performed followed by shifting elements to the right.

Let’s see the program to understand it more clearly.

Method: Java Program to Insert an Element in a Sorted Array By Using Manual Shifting

Approach:

  1. In the main() method, call insert() method to get an updated array as output.
  2. In the user defined insert() method, traverse the array starting from the end.
  3. Check whether the current element is greater than the key to be inserted as the array is sorted.
  4. If condition passes shift the current element to one position ahead and then, at last, insert the key at its correct position.
  5. After insertion, return the updated size of the array.

Program:

public class Main 
{
    //main method
    public static void main(String[] args)
    {
        //array declared with size as 20
        int arr[] = new int[20];
        //array elements initialized
        arr[0] = 1;
        arr[1] = 2;
        arr[2] = 3;
        arr[3] = 4;
        arr[4] = 6;
       
        int size = 5;
        //value to be inserted
        int key = 5;
 
        System.out.print("Before Insertion: ");
        for (int i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
 
        // Inserting key (method call)
        size = insert(arr, key);
        
        System.out.print("\nAfter Insertion: ");
        for (int i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
    }

    // This function returns size+1 if insertion
    // is successful, else size (size of given array) .
    public static int insert(int arr[], int key)
    {
    
        int size = 5;
        int i;

      //Start traversing the array from end using for loop
      //check whether current element > key to be inserted
      for(i=size-1; (i >= 0 && arr[i] > key); i--)
      {

       // shift greater elements to the right if condition passes
            arr[i + 1] = arr[i];
      }

       // At last insert the key to its position
        arr[i + 1] = key;
         
        // return updated size of array
        return (size + 1);
    }
}
Output:

Before Insertion: 1 2 3 4 6 
After Insertion: 1 2 3 4 5 6

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core Java programs with the help of the Java basic programs list available.

Related Java Articles: