About the #sorting-algorithms series
The #sorting-algorithms series is a collection of posts about reimplemented sorting algorithms in JavaScript.
If you are not familiar with sorting algorithms, a quick introduction and the full list of reimplemented sorting algorithms can be found in the introduction post of the series on sorting algorithms in JavaScript.
If you feel comfortable with the concept of each sorting algorithm and only want to see the code, have a look at the summary post of the series. It removes all explanations and contains only the JavaScript code for all sorting algorithms discussed in the series.
Get the code on Github
Of course, all the code can also be found on Github in the repository sorting-algorithms-in-javascript.
A good way to compare all of them
Unlike the data structures, all sorting algorithms have the same goal and they can all take the same input data. So, for every sorting algorithms of the series, we are going sort an array
of 10 numbers from 1 to 10.
By doing so we will be able to compare the different sorting algorithms more easily. Sorting algorithms are very sensitive to the input data so we will also try different input data to see how they affect the performances.
The Merge sort algorithm
Definition
Merge sort is a divide and conquer algorithm. Conceptually, a Merge sort works as follows: 1) Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted), 2) Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list. From Wikipedia
Visualization
If you want to have a nice visualization of the algorithm, the visualgo.net website is a nice resource. You can play with many parameters and see which part of the algorithm is doing what.
Complexity
Time complexity | ||
---|---|---|
Best | Average | Worst |
O(n log(n)) | O(n log(n)) | O(n log(n)) |
To get a full overview of the time and space complexity of the Merge sort algorithm, have a look to this excellent Big O cheat sheet.
The code
For each sorting algorithm, we are going to look at 2 versions of the code. The first one is the final/clean version, the one that you should remember. The second one implements some counters in order to demonstrate the different time complexities depending of the inputs.
Clean version
// array to sort
var array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8];
// top-down implementation
function mergeSortTopDown(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 mergeTopDown(mergeSortTopDown(left), mergeSortTopDown(right));
}
function mergeTopDown(left, right) {
var array = [];
while(left.length && right.length) {
if(left[0] < right[0]) {
array.push(left.shift());
} else {
array.push(right.shift());
}
}
return array.concat(left.slice()).concat(right.slice());
}
console.log(mergeSortTopDown(array.slice())); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
// bottom-up implementation
function mergeSortBottomUp(array) {
var step = 1;
while (step < array.length) {
var left = 0;
while (left + step < array.length) {
mergeBottomUp(array, left, step);
left += step * 2;
}
step *= 2;
}
return array;
}
function mergeBottomUp(array, left, step) {
var right = left + step;
var end = Math.min(left + step * 2 - 1, array.length - 1);
var leftMoving = left;
var rightMoving = right;
var temp = [];
for (var i = left; i <= end; i++) {
if ((array[leftMoving] <= array[rightMoving] || rightMoving > end) &&
leftMoving < right) {
temp[i] = array[leftMoving];
leftMoving++;
} else {
temp[i] = array[rightMoving];
rightMoving++;
}
}
for (var j = left; j <= end; j++) {
array[j] = temp[j];
}
}
console.log(mergeSortBottomUp(array.slice())); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
Version with counters
// sample of arrays to sort
var arrayRandom = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8];
var arrayOrdered = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var arrayReversed = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
var countOuter = 0;
var countInner = 0;
var countSwap = 0;
function resetCounters() {
countOuter = 0;
countInner = 0;
countSwap = 0;
}
// top-down implementation
function mergeSortTopDown(array) {
countOuter++;
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 mergeTopDown(mergeSortTopDown(left), mergeSortTopDown(right));
}
function mergeTopDown(left, right) {
var array = [];
while(left.length && right.length) {
countInner++;
if(left[0] < right[0]) {
array.push(left.shift());
} else {
array.push(right.shift());
}
}
return array.concat(left.slice()).concat(right.slice());
}
mergeSortTopDown(arrayRandom.slice()); // => outer: 19 inner: 24 swap: 0
console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
resetCounters();
mergeSortTopDown(arrayOrdered.slice()); // => outer: 19 inner: 15 swap: 0
console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
resetCounters();
mergeSortTopDown(arrayReversed.slice()); // => outer: 19 inner: 19 swap: 0
console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
resetCounters();
// bottom-up implementation
function mergeSortBottomUp(array) {
var step = 1;
while (step < array.length) {
countOuter++;
var left = 0;
while (left + step < array.length) {
countInner++;
mergeBottomUp(array, left, step);
left += step * 2;
}
step *= 2;
}
return array;
}
function mergeBottomUp(array, left, step) {
var right = left + step;
var end = Math.min(left + step * 2 - 1, array.length - 1);
var leftMoving = left;
var rightMoving = right;
var temp = [];
for (var i = left; i <= end; i++) {
if ((array[leftMoving] <= array[rightMoving] || rightMoving > end) &&
leftMoving < right) {
temp[i] = array[leftMoving];
leftMoving++;
} else {
temp[i] = array[rightMoving];
rightMoving++;
}
}
for (var j = left; j <= end; j++) {
countSwap++;
array[j] = temp[j];
}
}
mergeSortBottomUp(arrayRandom.slice()); // => outer: 4 inner: 9 swap: 36
console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
resetCounters();
mergeSortBottomUp(arrayOrdered.slice()); // => outer: 4 inner: 9 swap: 36
console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
resetCounters();
mergeSortBottomUp(arrayReversed.slice()); // => outer: 4 inner: 9 swap: 36
console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
resetCounters();