fueanta

Merge Sort in Typescript

Jul 1st, 2021
973
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const merge = <T>(leftArray: T[], rightArray: T[]): T[] => {
  2.     const mergedArray: T[] = [];
  3.     let i: number = 0, j: number = 0;
  4.  
  5.     while (i < leftArray.length && j < rightArray.length) {
  6.         if (leftArray[i] < rightArray[j])
  7.             mergedArray.push(leftArray[i++]);
  8.         else
  9.             mergedArray.push(rightArray[j++]);
  10.     }
  11.  
  12.     return [...mergedArray, ...leftArray.slice(i), ...rightArray.slice(j)];
  13. };
  14.  
  15. const mergeSort = <T>(array: T[]): T[] => {
  16.     if (array.length < 2)
  17.         return array;
  18.  
  19.     const middle = ~~(array.length / 2);
  20.  
  21.     const leftArray = array.slice(0, middle);
  22.     const rightArray = array.slice(middle);
  23.  
  24.     return merge(
  25.         mergeSort(leftArray),
  26.         mergeSort(rightArray)
  27.     );
  28. };
  29.  
  30. export default mergeSort;
  31.  
RAW Paste Data