Skip to content

Commit b4346f9

Browse files
Create InsertionSort.js
Added Insertion Sort
1 parent 3116c38 commit b4346f9

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Algorithms/InsertionSort.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
function insertionSort(arr) {
2+
const n = arr.length;
3+
4+
for (let i = 1; i < n; i++) {
5+
let currentElement = arr[i];
6+
let j = i - 1;
7+
8+
while (j >= 0 && arr[j] > currentElement) {
9+
arr[j + 1] = arr[j];
10+
j--;
11+
}
12+
13+
arr[j + 1] = currentElement;
14+
}
15+
}
16+
17+
// Example usage:
18+
var arr = [7, 2, 1, 6, 5, 3, 8, 4];
19+
insertionSort(arr);
20+
console.log(arr.toString());

0 commit comments

Comments
 (0)