Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c04c45b

Browse files
Raj MhetarRaj Mhetar
Raj Mhetar
authored and
Raj Mhetar
committed
added merge sort code in js
1 parent 77274c2 commit c04c45b

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

SortingAlgorithms/mergeSort.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
function mergeSort(arr) {
2+
if (arr.length <= 1) {
3+
return arr;
4+
}
5+
6+
const mid = Math.floor(arr.length / 2);
7+
const left = mergeSort(arr.slice(0, mid));
8+
const right = mergeSort(arr.slice(mid));
9+
10+
return merge(left, right);
11+
}
12+
13+
function merge(left, right) {
14+
let result = [];
15+
let leftIndex = 0;
16+
let rightIndex = 0;
17+
18+
while (leftIndex < left.length && rightIndex < right.length) {
19+
if (left[leftIndex] < right[rightIndex]) {
20+
result.push(left[leftIndex]);
21+
leftIndex++;
22+
} else {
23+
result.push(right[rightIndex]);
24+
rightIndex++;
25+
}
26+
}
27+
28+
// Concat remaining elements
29+
return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex));
30+
}
31+
32+
// Example usage
33+
const arr = [38, 27, 43, 3, 9, 82, 10];
34+
const sortedArray = mergeSort(arr);
35+
console.log(sortedArray);

0 commit comments

Comments
 (0)