Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

mergeSort

export function mergeSort (arr){
  if(arr.length <= 1){
    return arr;
  }
  let mid = Math.floor(arr.length /2);
  return merge(
    mergeSort (arr.slice(0,mid)),
    mergeSort (arr.slice(mid))
  )
}

function merge(left,right) {
  let mergeArr = [];
  let i = 0,j = 0;

  while(i < left.length && j < right.length) {
    if(left[i] < right[j]){
      mergeArr.push(left[i++])
    
    }else {
      mergeArr.push(right[j++])
    }
  }
  return mergeArr.concat(left.slice(i)).concat(right.slice(j));
}
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #mergeSort
ADD COMMENT
Topic
Name
8+6 =