R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

{ Merge Sort }

The Question

Can you implement the merge sort algorithm?

Example

Given the array: [4, 2, 6, 2, 3]

The mergeSort function should return: [2, 2, 3, 4, 6]

PseudoCode

Visual Representation

One Possible Solution

function merge(left, right) {
    var outputArray = [];
    
    while(left.length && right.length) {
        if (left[0] < right[0]) outputArray.push(left.shift());
        else outputArray.push(right.shift());
    }
    
    while(left.length) {
        outputArray.push(left.shift());
    }
    
    while(right.length) {
        outputArray.push(right.shift());
    }

    return outputArray
}

function mergeSort(array) {
    if (array.length < 2) return array
    
    var middle = Math.floor(array.length / 2);
    var left = array.slice(0, middle);
    var right = array.slice(middle);
    
    return merge(mergeSort(left),mergeSort(right));
}

Efficiency  

  • Time Efficiency in all cases (best and worst): O(n log(n))

Since we divide each set to be sorted in half at each level of recursion, there will be log(n) levels.  A total of n comparisons must be made at each level, thus O(n log(n))

Solution

Merge Sort

By pat310

Merge Sort

Technical interview problem for implementing the merge sort algorithm

  • 1,760