You are here: Home / Topics / Insertion sort example in Java

Insertion sort example in Java

Filed under: Java on 2023-08-23 06:46:38

//  Program to SORT the Array elements using INSERTION SORT

class  InsertionSort
{
public static void main( String args[ ] )
{
 int  a[ ] = { 0, 20, 40, 10, 50, 30 };
 int i, n = 5;

 System.out.print( " The Unsorted Array is = " );
 for( i=1 ; i<=n ; i++ )
 {
  System.out.print( a[ i ] + " " );
 }

 int  tmp, j;
 a[0] = -2147483648;
 for( i=1 ; i<=n ; i++ )
 {
  tmp = a[ i ];
  j = i - 1;
  while( tmp < a[ j ] )
  {
   a[ j +1] = a[ j ];
   j--;
  }
  a[ j +1] = tmp;
 }

 System.out.print( "\n The Sorted Array is   = " );
 for( i=1 ; i<=n ; i++ )
 {
  System.out.print( a[ i ] + " " );
 }
}
}


Output:

Unorted Numbers  are =  20  40  10  50  30 
Sorted Numbers  are  =  10  20  30  40  50

About Author:
J
Java     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.