Merge Sort
Merge Sort is a stable comparison sort algorithm with exceptional performance. Merge Sort uses the merging method and performs at O(n log (n)) in the best, average, and worst case.
Table of contents
Performance
TIP — When you share this page, the preview image generated displays the algorithm's Big-O runtime!
Code
Walkthrough
The algorithm executes in the following steps:
- Initialize the main
mergeSort()
function passing in the array, the first index, and the last index. - Find the index in the middle of the first and last index passed into the
mergeSort()
function. Save this to a variable calledmiddle
. - Make 2 recursive calls to the
mergeSort()
function:- The first includes indexes from
0...middle
- The second includes indexes from
middle+1...lastIndex
- The first includes indexes from
These recursive calls will run until there is only one item passed into each subarray. At this point, the merge()
function is called to begin merging the smaller subarrays into a larger sorted array.
merge()
- The
merge()
function typically gets 4 parameters: the complete array and the starting, middle, and ending index of the subarray. The start, middle, and end index are used to create 2 subarrays, the first ranging from start to middle and second ranging from middle to end. At this point, each subarray is in the correct order. - The two subarrays are merged back together in order.