Skip to content

Commit fced0f0

Browse files
committed
add insertion sort
1 parent 88f04fa commit fced0f0

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

assets/img/insertion-sort.gif

111 KB
Loading

insertion-sort/README.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Insertion sort
2+
3+
<div align="center">
4+
<img src="https://github.com/iamlorddop/sorting-methods/blob/main/assets/img/insertion-sort.gif" alt="insertion-sort.gif">
5+
</div>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
let firstArray = [];
2+
let secondArray = [1, 1, 19, 4, 5];
3+
let thirdArray = [-1, 2, 4, -5, 10];
4+
let fourthArray = [-1, -5, -12, -2, 0];
5+
6+
// Generate an array with random numbers
7+
for(let i = 0; i < 5; i++) {
8+
firstArray.push(Math.round(Math.random() * 100));
9+
}
10+
11+
console.log(`Before sort 1 array: ${firstArray}\nBefore sort 2 array: ${secondArray}\nBefore sort 3 array: ${thirdArray}\nBefore sort 4 array: ${fourthArray}`);
12+
13+
function insertionSort(arr) {
14+
let key, j;
15+
for (let i = 1; i < arr.length; i++) {
16+
key = arr[i];
17+
j = i - 1;
18+
/* Move elements of arr[0..i-1], that are
19+
greater than key, to one position ahead
20+
of their current position */
21+
while (j >= 0 && arr[j] > key) {
22+
arr[j + 1] = arr[j];
23+
j = j - 1;
24+
}
25+
arr[j + 1] = key;
26+
}
27+
return arr;
28+
}
29+
30+
insertionSort(firstArray);
31+
insertionSort(secondArray);
32+
insertionSort(thirdArray);
33+
insertionSort(fourthArray);
34+
35+
console.log(`After sort 1 array: ${firstArray}\nAfter sort 2 array: ${secondArray}\nAfter sort 3 array: ${thirdArray}\nAfter sort 4 array: ${fourthArray}`);

0 commit comments

Comments
 (0)