Home » Java » Insertion Sort Algorithm with full code- Java

Insertion Sort Algorithm with full code- Java

In this tutorial, we are going to learn how to implement insertion sort in java. Insertion sort is a very popular and very useful algorithm in programming.

Here, I will create a class called “Sotrs” and a method called “insertionSort”. The method declared as a static method because we can call static methods directly without creating an instance of the corresponding class.

Also, there is an integer array called “arr1” with 5,2,4,6,1,3 elements. There are two for loop in the main method. The for loop number one will print the elements of the array before the sorting and the for loop number two will print the elements in the array two after the sorting.

In line 1, the insertionSort method will be called with a parameter. Here the parameter is our array.

Now we look at steps in the insertionSort method. The following figure explains the basic steps of the selection sort algorithm.

insertion sort steps
Insertion sort steps

Here, I will declare a variable called n. n will be assigned the length of the array. The for loop runs n times through the array. In the while loop, if the value of the key is less than the value of the current element, swap index numbers of both elements. Finally, the value of the key will be assigned to the left-hand side element.

public class Sorts {
    public static void main(String[] args) {
        int[] arr1 = {5,2,4,6,1,3};    
        System.out.println("Before Insertion Sort");
        // For loop number one    
        for(int i:arr1){    
            System.out.print(i+" ");    
        }  
  
        System.out.println();    
            
        //sorting array using insertion sort
        insertionSort(arr1);    // line 1
       
        System.out.println("After Insertion Sort"); 
        // For loop number two   
        for(int i:arr1){    
            System.out.print(i+" ");    
        } 
    }
    
    public static void insertionSort(int array[]) {
  
        int n = array.length;  

        for (int j = 1; j < n; j++) {  
            int key = array[j];  
            int i = j-1;  
            while ( (i > -1) && ( array [i] > key ) ) {  
                array [i+1] = array [i];  
                i--;  
            }  
            array[i+1] = key;  
        }  
    }
}

Please follow us:
error

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

FACEBOOK
FACEBOOK
YOUTUBE
YOUTUBE