Merge Sort
Youtube Link :
Code :
Code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | function mergeArray(arr1,arr2){ let result=[]; let i=0; let j=0; while(i<arr1.length && j<arr2.length){ if(arr1[i]<arr2[j]){ result.push(arr1[i]); i++; } else{ result.push(arr2[j]); j++; } } while(i<arr1.length){ result.push(arr1[i]); i++; } while(j<arr2.length){ result.push(arr2[j]); j++; } return result; } function mergeSort(array){ if(array.length<=1) return array; let mid = Math.floor(array.length/2); let left = mergeSort(array.slice(0,mid)); let right = mergeSort(array.slice(mid)); return mergeArray(left,right); } mergeSort([6,3,2,9,1,23,65,34]); |