zoukankan      html  css  js  c++  java
  • 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
            }
        }
    }
  • 相关阅读:
    抽象类abstract
    final关键字特点
    继承ExtendsFour
    继承(继承中构造方法的关系)
    继承ExtendsTwo-super&this
    继承ExtendsOne
    静态
    构造方法与setXxx方法
    15.8
    15.7
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13151264.html
Copyright © 2011-2022 走看看