Insertion Sort

package _Sort.Algorithm

/**
 * Insertion Sort
 * https://www.geeksforgeeks.org/insertion-sort/
 * Insertion Sort is a simple sorting algorithm that works the way we sort playing cards in our hands.
 * Loop from i=1 to n-1: Pick element arr[i] and insert it into sorted sequence arr[0..i-1]
 * Best Time complexity are O(n);
 * Worst/Average Time complexity are O(n*n);
 * Space complexity is O(1), In-Place algorithm;
 * Stable;
 * */
class InsertionSort {
    fun sort(array: IntArray): Unit {
        //Loop from i=1 to n-1
        for (i in 1 until array.size) {
            val key = array[i]
            var j = i - 1
            //move element of arr[i-1] that are greater than key,
            //to one position ahead of their current position
            /*
            * for example:4,3,2;
            * 1.key=3, j is index:0, array[j] = 4,
            * 2.if (4>3) 4 and 3 switch position and update j;
            * 3.put key into the correct position
            * */
            while (j >= 0 && array[j] > key) {
                array[j+1] = array[j]
                j--
            }
            //put key into the correct position
            array[j+1] = key
        }
    }
}

 

你可能感兴趣的:(Insertion Sort)