public class InsertionSort {

    public static void main(String[] args) {
        int[] array = new int[]{5, 3, 9, 1, 6, 4, 10, 2, 8, 7, 15, 3, 2};

        System.out.println("Before: " + Arrays.toString(array));
        sort(array);
        System.out.println("After:  " + Arrays.toString(array));
    }

    public static void sort(int[] arr) {
        // This sort algorithm is similar with Bubble sort, the difference is that Bubble always find the
        // minimum of the sub array and swap it to the head of the subarray.

        // The core idea of insertion sort is that make the small scale sub array ordered, then every time enlarge
        // the size of sub arrays by 1 slot meanwhile place the newly added element in proper position so that the
        // new sub array is still ordered.
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j > 0; j--) {
                if (arr[j - 1] <= arr[j]) {
                    break;
                }

                swap(arr, j - 1, j);
            }
        }
    }

    private static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-03 14:51:26

results matching ""

    No results matching ""