Merge Sort
Approach\nusing mergesort algorithm\n\n# Complexity\n- Time complexity: nlog(n)\n\n- Space complexity: nlog(n)\n\n# Code\n/**\n * @param {Array} arr #- The inpu
# Approach\nusing mergesort algorithm\n\n# Complexity\n- Time complexity: nlog(n)\n\n- Space complexity: nlog(n)\n\n# Code\n```/**\n * @param {Array} arr #- The input array to be sorted.\n * @param {Function} fn #- A custom comparison function used for sorting.\n * @return {Array} #- A new array containing the sorted elements.\n */\nvar sortBy = function (arr, fn) {\n  return mergesort(0, arr.length - 1, arr, fn); // Call the merge sort algorithm with initial parameters.\n};\n\nfunction mergesort(s, e, arr, fn) {\n  if (s >= e) return; // If the array size is 0 or 1, it\'s already sorted, so return.\n  let m = Math.floor((s + e) / 2); // Calculate the middle index.\n  mergesort(s, m, arr, fn); // Recursively sort the left half.\n  mergesort(m + 1, e, arr, fn); // Recursively sort the right half.\n  merge(s, m, e, arr, fn); // Merge the two sorted halves.\n}\n\nfunction merge(s, m, e, arr, fn) {\n  let arr1 = arr.slice(s, m + 1); // Create a copy of the left subarray.\n  let arr2 = arr.slice(m + 1, e + 1); // Create a copy of the right subarray.\n  let i = 0,\n    j = 0,\n    st = s;\n  while (i < arr1.length && j < arr2.length) {\n    if (fn(arr1[i]) < fn(arr2[j])) {\n      arr[st] = arr1[i]; // Place the smaller element from arr1 into the result array.\n      i++;\n    } else {\n      arr[st] = arr2[j]; // Place the smaller element from arr2 into the result array.\n      j++;\n    }\n    st++;\n  }\n  while (i < arr1.length) {\n    arr[st] = arr1[i]; // Copy any remaining elements from arr1.\n    i++;\n    st++;\n  }\n  while (j < arr2.length) {\n    arr[st] = arr2[j]; // Copy any remaining elements from arr2.\n    j++;\n    st++;\n  }\n}\n\n```
['Merge Sort', 'JavaScript']