How to Implement Insertion Sort in Java


This tutorial will show us the method of insertion sort in Java.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class InsertSortExample {

    public static void main(String[] args) {

        int[] arr = {10,34,235,22,1,93};

        sort(arr);

        System.out.println(Arrays.toString(arr));

    }

    private static void sort(int[] arr) {
    	
        int len = arr.length;
        int insertNum;// insert value 
        for(int i = 1;i = 0 && arr[j] > insertNum){// circulate from back to front
                arr[j+1] = arr[j];
                j--;
            }
            arr[j+1] = insertNum;// insert current value
        }
    }
}

Output:

[1, 10, 22, 34, 93, 235]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments