Skip to content

Commit

Permalink
Create mergeSort.js
Browse files Browse the repository at this point in the history
  • Loading branch information
Pazmy authored Oct 22, 2020
1 parent 9f2c36f commit e8d527f
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions JavaScript programs/mergeSort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
function mergeSort(array,half = array.length/2){

if(array.length < 2){
return array
}

const left = array.splice(0,half);

return merger(mergeSort(left),mergeSort(array))
}

function merger(left_part,right_part){

const arr = [];

while(left_part.length && right_part.length){
if(left_part[0] < right_part[0]){
arr.push(left_part.shift())
}else{
arr.push(right_part.shift())
}
}

return [...arr,...left_part,...right_part];
}

console.log(mergeSort([2,9,4,1,3,7,3,10,5,6]));

0 comments on commit e8d527f

Please sign in to comment.