Insertion Sort in Java Program

Insertion Sort is a sorting technique used for which sorting. Insertion Sort is good for small elements only because it requires more time for sorting large number of elements. There different kinds of sorting technique like Selection Sort and Bubble Sort.

A very good example of Insertion Sort is while we playing cards.

Java Program - Insertion Sort

public class InsertSortExample{

    public static void InsertionSort(int arr[]){
        
        int n = arr.length;
        
        for(int i=1; i<n; i++){
            
            int key = arr[i];
            
            int j = i-1;
            
            while((j>-1) && (arr[j]>key)){
                arr[j+1]=arr[j];
                j--;
            }
            
            arr[j+1] = key;  
            
        }
        
    }
    
    public static void main(String []args){
       
        int arr[] = {6,5,3,1,8,7,2,4}; 
        
        System.out.println("Before Insertion Sort");  
        for(int i: arr){
            System.out.print(i+"  ");
        }
        
        InsertionSort(arr);
        
        System.out.println("\n\nAfter InsertionSort Sort");  
        for(int i: arr){
            System.out.print(i+"  ");
        }
        
    }
}

Comments