Posts

Showing posts with the label learn mergeSort in js

Learning MergeSort with JS

  Today I learn MergeSort in JS! I Learned mergeSort because this is the fastest sorting algorithm, as it takes O(n log n) time, which is better than bubble sort with time complexity O(n^2). At the end, I understood the main logic of MergeSort, the divide-and-conquer method. which means an array pass to merge_sort(arr), it starts by dividing into subarrays until it reaches 1 element of subarray, then it starts sorting it .  merge-sort.js function merge_sort(arr, l = 0 , h = arr.length - 1 ) {         if (l >= h) return     let m = Math. floor ((l + h) / 2 )     merge_sort (arr, l, m)     merge_sort (arr, m + 1 , h)     merge (arr, l, m, h) } function merge(arr, l, m, h) {         const tmp = []     let i = l, j = m + 1     while (i <= m && j <= h) {         if (arr[i] < arr[j]) tmp. push (arr[i ++ ])       ...