码迷,mamicode.com
首页 > 编程语言 > 详细

[Algorithms] Sort an Array with a Nested for Loop using Insertion Sort in JavaScript

时间:2018-12-21 13:25:28      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:nested   for loop   exit   rip   com   turn   bsp   get   console   

nsertion sort is another sorting algorithm that closely resembles how we might sort items in the physical world. We start at the second item in our collection and make the assumption that this item is a sorted list of length 1. We then compare all the items before it and determine if it needs to be "inserted" to the left or right of our item. We then move onto the second item, again comparing it to every item before it in the list, inserting those items correctly.

Because this algorithm requires two loops, one inside the other, the worst case scenario of our algorithm still requires a time complexity of O(n^2). This is also an inefficient sorting algorithm, but if our list is mostly sorted already, it will perform a slight bit better than bubble sort.

 

function insertionSort (array) {
    let i = 0
    let j = 0

    for (i = 1; i < array.length; i++) {
        for (j = 0; j < i; j++) {
            if (array[i] < array[j]) {
                const [item] = array.splice(i, 1); // get the item on ith position
                array.splice(j, 0, item);// insert the item on jth position
            }
        }
    }

    return array;
}

let numbers = [10, 5, 6, 3, 2, 8, 9, 4, 7, 1]

console.log(insertionSort(numbers))

  

[Algorithms] Sort an Array with a Nested for Loop using Insertion Sort in JavaScript

标签:nested   for loop   exit   rip   com   turn   bsp   get   console   

原文地址:https://www.cnblogs.com/Answer1215/p/10153589.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!