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
            }
        }
    }
  • 相关阅读:
    zabbix4.4安装和简要设置
    SAMBA服务
    NFS服务
    Rsync+inotify数据同步
    Linux上FTP部署:基于mariadb管理虚拟用户
    rsyslog日志服务部署
    Typora自动生成标题编号
    编译安装LAMP
    303. 区域和检索
    [leetcode]53. 最大子序和*
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13151264.html
Copyright © 2011-2022 走看看