Skip to content

Commit d4c64ac

Browse files
authored
Create insertionSort.js
1 parent abc3874 commit d4c64ac

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

sorting/insertionSort.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
function insertionSort (items) {
2+
for (var i = 0; i < items.length; i++) {
3+
let value = items[i]
4+
// store the current item value so it can be placed right
5+
for (var j = i - 1; j > -1 && items[j] > value; j--) {
6+
// loop through the items in the sorted array (the items from the current to the beginning)
7+
// copy each item to the next one
8+
items[j + 1] = items[j]
9+
}
10+
// the last item we've reached should now hold the value of the currently sorted item
11+
items[j + 1] = value
12+
}
13+
14+
return list
15+
}
16+
17+
const list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
18+
console.log(insertionSort(list)) // [ 17, 20, 26, 31, 44, 54, 55, 77, 93 ]

0 commit comments

Comments
 (0)