codescracker


java

Java Program Insertion Sort



« Previous Program Next Program »


Insertion Sort

To sort an array using insertion sort technique in Java Programming, you have to ask to the user to enter the array size and array elements in random order, now start sorting the elements of the array in ascending order using the insertion sort technique as shown in the following program.

Java Programming Code for Insertion Sort

Following Java Program ask to the user to enter array size and array elements to sort the array using the insertion sort technique, then display the sorted array on the screen:

/* Java Program Example - Insertion Sort */
		
import java.util.Scanner;

public class JavaProgram
{
   public static void main(String args[])
   {
       int size, i, j, temp;
       int arr[] = new int[50];
       Scanner scan = new Scanner(System.in);
	   
       System.out.print("Enter Array Size : ");
       size = scan.nextInt();
	   
       System.out.print("Enter Array Elements : ");
       for(i=0; i<size; i++)
       {
           arr[i] = scan.nextInt();
       }
	   
       System.out.print("Sorting Array using Insertion Sort Technique..\n");
       for(i=1; i<size; i++)
       {
           temp = arr[i];
           j = i - 1;
           while((temp < arr[j]) && (j >= 0))
           {
               arr[j+1] = arr[j];
               j = j - 1;
           }
           arr[j+1] = temp;
       }
	   
       System.out.print("Array after Sorting is : \n");
       for(i=0; i<size; i++)
       {
           System.out.print(arr[i] + "  ");
       }
   }
}

When the above Java Program is compile and executed, it will produce the following output:

Java Program insertion sort

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test