Skip to content

Commit d2e9261

Browse files
committed
Isertion sort
1 parent afbb8d2 commit d2e9261

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// The Insertion sort algorithm
2+
3+
// Definition
4+
5+
// Insertion sort algorithm iterates, consuming one input element each repetition,
6+
// and growing a sorted output list. Each iteration removes one element from the input data,
7+
// finds the location it belongs within the sorted list, and inserts it there.
8+
// It repeats until no input elements remain. From Wikipedia
9+
10+
// This algorithm is often compared to how as human we would sort a card game for example.
11+
12+
// array to sort
13+
var array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8];
14+
15+
function insertionSort(array) {
16+
for(var i = 0; i < array.length; i++) {
17+
var temp = array[i];
18+
var j = i - 1;
19+
while (j >= 0 && array[j] > temp) {
20+
array[j + 1] = array[j];
21+
j--;
22+
}
23+
array[j + 1] = temp;
24+
}
25+
return array;
26+
}
27+
28+
console.log(insertionSort(array)); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

0 commit comments

Comments
 (0)