Sorts an array using the Merge Sort algorithm.
The type of elements in the array.
The array to be sorted.
A comparison function that defines the sorting order. Should return a positive number if a > b, 0 if a === b, and a negative number if a < b.
a > b
a === b
a < b
The sorted array.
// Sorting an array of numbersconst arr = [3, 1, 4, 1, 5];const sortedArr = mergeSort(arr, (a, b) => a - b);console.log(sortedArr); // [1, 1, 3, 4, 5] Copy
// Sorting an array of numbersconst arr = [3, 1, 4, 1, 5];const sortedArr = mergeSort(arr, (a, b) => a - b);console.log(sortedArr); // [1, 1, 3, 4, 5]
// Sorting an array of stringsconst arr = ['banana', 'apple', 'cherry'];const sortedArr = mergeSort(arr, (a, b) => a.localeCompare(b));console.log(sortedArr); // ['apple', 'banana', 'cherry'] Copy
// Sorting an array of stringsconst arr = ['banana', 'apple', 'cherry'];const sortedArr = mergeSort(arr, (a, b) => a.localeCompare(b));console.log(sortedArr); // ['apple', 'banana', 'cherry']
Sorts an array using the Merge Sort algorithm.