zoukankan      html  css  js  c++  java
  • Insertion Sort

    (referrence: GeeksforGeeks)

    Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.

    Insertion Sort

    Algorithm
    // Sort an arr[] of size n
    insertionSort(arr, n)
    Loop from i = 1 to n-1.
    ……a) Pick element arr[i] and insert it into sorted sequence arr[0…i-1]

    Example: 
    12, 11, 13, 5, 6

    Let us loop for i = 1 (second element of the array) to 5 (Size of input array)

    i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12
    11, 12, 13, 5, 6

    i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 13
    11, 12, 13, 5, 6

    i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one position ahead of their current position.
    5, 11, 12, 13, 6

    i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position ahead of their current position.
    5, 6, 11, 12, 13

     1 class Solution {
     2     public static void insertionSort(int[] nums) {
     3         for (int i = 1; i < nums.length; i++) {
     4             key = nums[i];
     5             int j = i - 1;
     6 
     7             while (j >= 0 && nums[j] > key) {
     8                 nums[j + 1] = arr[j]
     9                 j--;
    10             }
    11             nums[j + 1] = key;
    12         }
    13     }
    14 }

    Time complexity O(n^2), space cost O(1), and it's in-place sorting.

  • 相关阅读:
    oralce索引的使用
    oracle中connect by prior的使用
    oracle函数listagg使用
    oracle函数的使用
    redis高可用集群搭建
    Node.js安装及环境配置之Windows篇
    Repeater 合并单元格
    c#16进制转浮点数单精度类型
    EF Core 实体映射表或视图
    docker 构建filebeat镜像
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4856695.html
Copyright © 2011-2022 走看看