Array Merge Sort Code in JavaScript and its Big-O

Array Merge Sort Code in JavaScript



function mergeSort(arr) {
    if (arr.length === 1) {
        return arr;
    }
    let mid = Math.floor(arr.length / 2);
    let leftArr = arr.slice(0,mid);
    let rightArr = arr.slice(mid);
    
   return merge(mergeSort(leftArr),  mergeSort(rightArr));
    
}
function megre (leftArr, rightArr) {
    let output = [];
    while (leftArr.length && rightArr.length) {
     if (leftArr[0] < rightArr[0]) {
         output.push(leftArr.shift()); 
      } else {
         output.push(rightArr.shift()); 
      }
    }
    return [...output, ...leftArr, ...rightArr];
}

Merge Sort complexity or BigO is O(n log n) in best, average and worst case scenarios.

Leave a Reply

Your email address will not be published. Required fields are marked *