Merge Sort Algorithm
An efficient, stable, divide-and-conquer sorting algorithm with O(n log n) time complexity.
Starting merge sort algorithm
DividingComparingMergingSorted
1function mergeSort(arr) {
2 // Base case: arrays with 0 or 1 element are already sorted
3 if (arr.length <= 1) {
4 return arr;
5 }
6
7 // Split the array into two halves
8 const middle = Math.floor(arr.length / 2);
9 const left = arr.slice(0, middle);
10 const right = arr.slice(middle);
11
12 // Recursively sort and merge the two halves
13 return merge(
14 mergeSort(left),
15 mergeSort(right)
16 );
17}
18
19// Helper function to merge two sorted arrays
20function merge(left, right) {
21 let result = [];
22 let i = 0, j = 0;
23
24 // Compare elements from both arrays and add smaller one to result
25 while (i < left.length && j < right.length) {
26 if (left[i] < right[j]) {
27 result.push(left[i++]);
28 } else {
29 result.push(right[j++]);
30 }
31 }
32
33 // Add any remaining elements
34 return result.concat(left.slice(i)).concat(right.slice(j));
35}