Skip to content

Commit d311500

Browse files
committed
implemented insertion sort using javascript
1 parent 2129f5e commit d311500

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
function insertionSort(inputArr) {
2+
3+
let n = inputArr.length;
4+
5+
for (let i = 1; i < n; i++) {
6+
// Choosing the first element in the unsorted subarray
7+
let current = inputArr[i];
8+
9+
// The last element of the sorted subarray
10+
let j = i - 1;
11+
12+
while ((j > -1) && (current < inputArr[j])) {
13+
inputArr[j + 1] = inputArr[j];
14+
j--;
15+
}
16+
17+
inputArr[j + 1] = current;
18+
}
19+
20+
return inputArr;
21+
}
22+
23+
let inputArr = [5, 2, 4, 6, 1, 3];
24+
25+
insertionSort(inputArr);
26+
27+
console.log(inputArr);

0 commit comments

Comments
 (0)