Simple Insertion Sort in Java

Insertion sort is one of basic sorting algorithms.

public class InsertionSort {
    public static void main(String[] args) {
        int[]arr={56,65,4,54,24,8,74,85};
        insertionsort(arr);
        printarray(arr);
    }
    public static void insertionsort(int[] arr){
        int len=arr.length,temp;
        for(int i=0;i<len;i++){
            temp=arr[i];
            int j=i-1;
            while ((j>-1)&&(arr[j]>temp)){
                arr[j+1]=arr[j];
                j--;
            }
            arr[j+1]=temp;

        }
    }
    public static void printarray(int[] arr){
        for (int j : arr) System.out.print(j + " ");
    }
}

Leave a Comment

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

Scroll to Top