Consistently efficient divide-and-conquer
Merge Sort is a legendary sorting algorithm that uses the Divide and Conquer strategy. It breaks down an array into single-element sub-arrays, then merges them back together in a sorted order. Unlike other basic sorts, its performance is always $O(n \log n)$.
Press "Start Sorting" to begin
Merge Sort is a stable sort that follows the principle of Merge: two sorted lists can be merged into a single sorted list in $O(n)$ time. By recursively splitting the unsorted list, we create a binary tree with $\log n$ levels of depth.
Because the array is halved at each step, there are exactly $\lceil \log_2(n) \rceil$ levels of recursion. This is why the log factor appears.
Standard Merge Sort is not "in-place." It requires $O(n)$ extra space to store the temporary sub-arrays during the merge phase.
1function mergeSort(arr) {2 if (arr.length <= 1) return arr;3 4 const mid = arr.length / 2;5 const left = mergeSort(arr.slice(0, mid));6 const right = mergeSort(arr.slice(mid));7 8 return merge(left, right);9}Merge Sort is the backbone of Java's Arrays.sort() for objects and Python's Timsort (which is a hybrid of Merge and Insertion Sort).
1def merge_sort(arr):2 if len(arr) <= 1:3 return arr4 5 mid = len(arr) // 26 left = merge_sort(arr[:mid])7 right = merge_sort(arr[mid:])8 9 return merge(left, right)10 11def merge(left, right):12 result = []13 i = j = 014 while i < len(left) and j < len(right):15 if left[i] < right[j]:16 result.append(left[i])17 i += 118 else:19 result.append(right[j])20 j += 121 result.extend(left[i:])22 result.extend(right[j:])23 return result1function mergeSort(arr) {2 if (arr.length <= 1) return arr;3 4 const mid = Math.floor(arr.length / 2);5 const left = mergeSort(arr.slice(0, mid));6 const right = mergeSort(arr.slice(mid));7 8 return merge(left, right);9}10 11function merge(left, right) {12 let result = [];13 while (left.length && right.length) {14 if (left[0] < right[0]) {15 result.push(left.shift());16 } else {17 result.push(right.shift());18 }19 }20 return [...result, ...left, ...right];21}