Java Program to Insert an Element in an Unsorted Array

In the previous article, we have seen Java Program to Insert an Element in a Sorted Array

In this article, we will learn how to enter an element at a specified position in an unsorted array by using Java Programming language.

Java Program to Insert an Element in an Unsorted Array

Prerequisite: 

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

In an unsorted array Initially, we have to search for the specified position then we can directly insert the element into that position. Here we need not check any condition before inserting.

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

Method: Java Program to Insert an Element in an Unsorted Array By Manually Right Shifting

Approach:

  1. In the user defined insert() method, traverse the array starting from the end to the specified position.
  2. Shift the current element one position ahead or to the right then when we reached the position insert the key to the specified position.
  3. After insertion, return the updated size of the array.
  4. In the main() method, call insert() method to get an updated array as output.

Program:

public class Main 
{
    //main() method
    public static void main(String[] args)
    {
        //array declared with array size as 20
        int arr[] = new int[20];
        arr[0] = 7;
        arr[1] = 2;
        arr[2] = 9;
        arr[3] = 23;
        arr[4] = 6;
       
        int size = 5;
        int key = 42;
 
        System.out.print("Before Insertion: ");
        for (int i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
            
        //System.out.println(size);
 
        // Inserting key (method call)
        size = insert(arr, key);
        
       // System.out.println(size);
 
        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 a given array).
    public static int insert(int arr[], int key)
    {
        int size = 5;
        // position  = index + 1
        int position = 2;
        int i;
        
       //Start traversing the array from end using for loop
       for(i=size-1; i >= position; i--)
       {
            // shift elements to the right 
            arr[i + 1] = arr[i];
        }

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

Before Insertion: 7 2 9 23 6 
After Insertion: 7 2 42 9 23 6

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Related Java Articles: