博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Algorithms] Insertion sort algorithm using TypeScript
阅读量:5157 次
发布时间:2019-06-13

本文共 990 字,大约阅读时间需要 3 分钟。

Insertion sort is a very intuitive algorithm as humans use this pattern naturally when sorting cards in our hands.

In this lesson, using TypeScript / Javascript, we’ll cover how to implement this algorithm, why this algorithm gets its name, and the complexity of our implementation of the insertion algorithm.

 

/** * ary: [4,3,2,1] *  * i = 1:  * current 3 * j = 0 --> array[j + 1] = array[j] --> [4, 4] * j = -1 --> array[j + 1] = current -->[3, 4] *  * i = 2:  * current: 2 * j = 1 --> array[j + 1] = array[j] --> [3,4,4] * j = 0 --> array[j + 1] = array[j] --> [3,3,4] * j = -1 --> array[j + 1] = current --> [2,3,4] */

 

function insertionSort(ary) {  let array = ary.slice();  for (let i = 1; i < array.length; i++) {    let current = array[i];    let j = i - 1;    while (j >= 0 && array[j] > current) {      // move the j to j+1      array[j + 1] = array[j];      j--;    }    // j = -1    array[j + 1] = current;  }  return array;}

 

 

转载于:https://www.cnblogs.com/Answer1215/p/9470725.html

你可能感兴趣的文章
centos 引导盘
查看>>
Notes of Daily Scrum Meeting(12.8)
查看>>
Apriori算法
查看>>
onlevelwasloaded的调用时机
查看>>
求出斐波那契数组
查看>>
lr_start_transaction/lr_end_transaction事物组合
查看>>
CodeIgniter学习笔记(四)——CI超级对象中的load装载器
查看>>
.NET CLR基本术语
查看>>
ubuntu的home目录下,Desktop等目录消失不见
查看>>
建立,查询二叉树 hdu 5444
查看>>
[Spring框架]Spring 事务管理基础入门总结.
查看>>
2017.3.24上午
查看>>
Python-常用模块及简单的案列
查看>>
(VC/MFC)多线程(Multi-Threading) -1. 基本概念.
查看>>
LeetCode 159. Longest Substring with At Most Two Distinct Characters
查看>>
LeetCode Ones and Zeroes
查看>>
基本算法概论
查看>>
jquery动态移除/增加onclick属性详解
查看>>
JavaScript---Promise
查看>>
暖暖的感动
查看>>