Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 37: Write a Java program to perform insertion sort.

Insertion.java

import java.util.Scanner;

//Class SelectionSort contains the method to perform InsertionSort.
class InsertionSort
{
	public static void insertionSort(int[] arr)
	{
		//Method to perform insertion sort.
        for(int i=1; i < arr.length;i++)
        {
            int temp=arr[i];
            int j=i-1;
            while(j>=0 && temp < arr[j])
            {
                arr[j+1]=arr[j];
                j--;
            }
            arr[j+1]=temp;
        }
	}
}

//Main class
public class  Insertion
{
	//Method to take input.
	public static int[] takeInput()
	{
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the number of elements to be included in the array.");
		int size = s.nextInt();
		int arr[] = new int[size];
		
		System.out.println("Enter the element in the array");
		for (int i = 0; i < size; i++)
		{
			arr[i] = s.nextInt();
		}
		return arr;
	}
	
	//Method to print sorted array.
	public static void print(int[] arr)
	{
		for (int i = 0; i < arr.length; i++)
		{
			System.out.print(arr[i]+" ");
		}
	}
	
	//Main method.
	public static void main(String[] args)
	{
		int[] arr = takeInput();
		InsertionSort.insertionSort(arr);
		System.out.println("Sorted Array");
		print(arr);
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.