Preview:
public class InsertionSort {
    public static void main(String[] args) {
        int[] arr = { 5, 2, 8, 3, 9, 1 };
        insertionSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    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 >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = key;
        }
    }
}
In this program, we have defined a method called insertionSort() that takes an integer array as an argument. It uses the insertion sort algorithm to sort the array in ascending order.

The insertionSort() method iterates over the array starting from the second element (i.e., index 1). For each element, it compares it with the elements before it and shifts them one position to the right until it finds the correct position for the current element. Finally, it inserts the current element into the correct position.

The main() method is used to test the insertionSort() method by passing an unsorted array to it and printing the sorted array.





downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter