Java Program to Implement Insertion Sort

What is Insertion Sort?

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.

Problem Description

Create a Java program to perform an insertion sort and further analyze its efficiency.

Insertion Sort Algorithm:

1. We will store the random set of numbers in an array.
2. We will traverse this array and insert each element of this array, to its correct position where it should actually be, by shifting the other elements on the left if required.
3. The first element in the array is considered as sorted, even if it is an unsorted array. The array is sub-divided into two parts, the first part holds the first element of the array which is considered to be sorted and second part contains all the remaining elements of array.
4. With each iteration one element from the second part is picked and inserted into the first part of array at its correct position by shifting the existing elements if required.
5. This goes until the last element in second part of array is placed in correct position in the output array.
6. Now, we have the array in sorted order.

Insertion Sort Example:

If we have the array as {50,20,60,90,40}
and we apply insertion sort to sort the array,
then the resultant array after each iteration will be as follows:

             Original array: {50, 20, 60, 90, 40}

Array after first iteration is     20 ->  50    ->  60   ->   90   ->   40
Array after second iteration is    20 ->  50    ->  60   ->   90   ->   40
Array after third iteration is     20 ->  50    ->  60   ->   90   ->   40
Array after fourth iteration is    20 ->  40    ->  50   ->   60   ->   90
            
               Sorted array is  20  40  50  60  90
Program/Source Code

Here is the source code of the Java Program to implement Insertion Sort. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. /*
  2.  * Java Program to Implement Insertion Sort
  3.  */
  4.  
  5. import java.util.Scanner;
  6.  
  7. /* Class InsertionSort */
  8. public class InsertionSort 
  9. {
  10.     /* Insertion Sort function */
  11.     public static void sort( int arr[] )
  12.     {
  13.         int N = arr.length;
  14.         int i, j, temp;
  15.         for (i = 1; i< N; i++) 
  16.         {
  17.             j = i;
  18.             temp = arr[i];    
  19.             while (j > 0 && temp < arr[j-1])
  20.             {
  21.                 arr[j] = arr[j-1];
  22.                 j = j-1;
  23.             }
  24.             arr[j] = temp;            
  25.         }        
  26.     }    
  27.     /* Main method */
  28.     public static void main(String[] args) 
  29.     {
  30.         Scanner scan = new Scanner( System.in );        
  31.         System.out.println("Insertion Sort Test\n");
  32.         int n, i;
  33.         /* Accept number of elements */
  34.         System.out.println("Enter number of integer elements");
  35.         n = scan.nextInt();
  36.         /* Create integer array on n elements */
  37.         int arr[] = new int[ n ];
  38.         /* Accept elements */
  39.         System.out.println("\nEnter "+ n +" integer elements");
  40.         for (i = 0; i < n; i++)
  41.             arr[i] = scan.nextInt();
  42.         /* Call method sort */
  43.         sort(arr);
  44.         /* Print sorted Array */
  45.         System.out.println("\nElements after sorting ");        
  46.         for (i = 0; i < n; i++)
  47.             System.out.print(arr[i]+" ");            
  48.         System.out.println();                     
  49.     }    
  50. }
Program Explanation

1. Using a for loop, we are reading n elements from standard input into an array named arr.
2. Next, we are comparing elements of the array so that we can insert them in the proper position using the insertion sort method.
3. At the end, we are printing/displaying the sorted array.

advertisement
advertisement

Time Complexity: O(N)
The worst and average case time complexity of insertion sort algorithm is O(N2) while the best case time complexity of insertion sort is O(N).

Space Complexity: O(1)
The space complexity for insertion sort is O(1) if we only consider the order of space used excluding the array.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Runtime Test Cases

Testcase 1:

Insertion Sort Test
 
Enter number of integer elements
20
 
Enter 20 integer elements
999 921 823 816 767 712 698 657 532 412 391 323 287 256 225 162 123 64 24 6
 
Elements after sorting
6 24 64 123 162 225 256 287 323 391 412 532 657 698 712 767 816 823 921 999

Testcase 2:

advertisement
Insertion Sort Test
 
Enter number of integer elements
20
 
Enter 20 integer elements
12 34 68 79 123 145 178 213 253 276 298 301 498 512 633 792 888 912 950 991
 
Elements after sorting
12 34 68 79 123 145 178 213 253 276 298 301 498 512 633 792 888 912 950 991

Testcase 3:

Insertion Sort Test
 
Enter number of integer elements
20
 
Enter 20 integer elements
54 135 23 75 1 576 234 928 13 84 631 1283 748 124 54 6 24 485 1024 0
 
Elements after sorting
0 1 6 13 23 24 54 54 75 84 124 135 234 485 576 631 748 928 1024 1283

To practice programs on every topic in Java, please visit “Programming Examples in Java”, “Data Structures in Java” and “Algorithms in Java”.

advertisement

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.