Merge Sort & Radix Sort

Merge Sort & Radix Sort

Merging Arrays Pseudocode

  • Create an empty array, take a look at the smallest values in each input array

  • While there are still values that we haven't looked at...

    • If the value in the first array is smaller than the value in the second array, push the value in the first array into our results and move on to the next value in the first array

    • If the value in the first array is larger than the value in the second array, push the value in the second array into our results and move on to the next value in the second array

    • Once we exhaust one array, push in all remaining values from the other array

function merge(arr1, arr2) {
    let results = [];
    let i = 0;
    let j = 0;
    while (i < arr1.length && j < arr2.length) {
        if(arr2[j] > arr1[i]) {
            results.push(arr1[i]);
            i++;
        } else {
            results.push(arr2[j]);
            j++;
        }
    }
    return results;
}

MergeSort Pseudocode

  • Break up the array into halves until you have the arrays that are empty or have one element

  • Once you have smaller sorted arrays, merge those arrays with other sorted arrays until you are back at the full length of the array

  • Once the array has been merged back together, return the merged array.

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

Time Complexity (Best) -> n log n

Time Complexity (Average) -> n log n

Time Complexity (Worst) -> n log n

Space Complexity -> n


Quick Sort Pseudocode

  • Call the pivot helper on the array

  • When the helper returns to you the updated pivot index, recursively call the pivot helper on the subarray to the left of that index, and the subarray to the right of that index

  • Your base case occurs when you consider a subarray with less than two elements.

Pivot function

function pivot(arr, start = 0, end = arr.length - 1) {
  const swap = (arr, idx1, idx2) => {
    [arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
  };

  let pivot = arr[start];
  let swapIdx = start;

  for (let i = start + 1; i <= end; i++) {
    if (pivot > arr[i]) {
      swapIdx++;
      swap(arr, swapIdx, i);
    }
  }

  swap(arr, start, swapIdx);
  return swapIdx;
}

pivot([4,8,2,1,5,7,6,3])


function quickSort(arr, left = 0, right = arr.lenght - 1) {
    if(left < right) {
        let pivotIndex = pivot(arr, left, right)
        quickSort(arr, left, pivotIndex-1);
        quickSort(arr, pivotIndex+1, right);
    }
    return arr;
}

Radix Sort

Radix Sort Helpers

getDigit(num, place) - returns the digit at the given place value

getDigit(12345, 0) // 5

getDigit(12345, 1) // 4

function getDigit(num, i) {
    return Math.floor(Math.abs(num) / Math.pow(10,i)) % 10;
}

function digitCount(num){
    if (num === 0) return 1;
    return Math.floor(Math.log10(Math.abs(num))) +1 ;
}

function mostDigits(nums) {
    let maxDigits = 0;
    for (let i = 0; i < nums.length; i++) {
        maxDigits = Math.max(maxDigits, digitCount(nums[i]));
    }
    return maxDigits;
}

Radix Sort Pseudocode

  • Define a function that accepts lists of numbers

  • Figure out how many digits the largest number has

  • Loop from k=0 up to this largest number of digits

  • For each iteration loop:

    • Create buckets for each digit ( 0 to 9 )

    • Place each number in the corresponding bucket based on its kth digit.

  • Replace our existing array with values in our buckets, starting with 0 and going up to 9

  • return list at the end

function radixSort(nums) {
    let maxDigitCount = mostDigit(nums);
    for (let k = 0; k < maxDigitCount; k++) {
        let digitBuckets = Array.from({length:10},() => []);
        for( let i = 0, i < nums.length; i++) {
             let digit = getDigits(nums[i], k); //3, 자리수에 해당하는 숫자
             digitBuckets[digit].push(nums[i]) // put it into bucktet
             // 3번째 어레이에 nums[0] 첫번째 숫자 추가
             // 2번째 어레이에 nums[1] 두번째 숫자는 2
            }
            nums = [].concat(...digitBuckets);
        }
        return nums;
    }

}

Radix Sort Big O

Time Complexity(Best) -> O(nk)

Time Complexity(Average) -> O(nk)

Time Complexity(Worse) -> O(nk)

Space Complexity -> O(n+k)