Merge Sort
Merge Sort is a popular comparison-based sorting algorithm known for its efficiency and stability. It employs a divide-and-conquer strategy to sort an array or list by recursively dividing it into smaller sub-arrays until each sub-array consists of a single element, then merging those sub-arrays to produce a sorted array.
The basic idea behind merge sort is this: it tends to be a lot easier to sort two smaller, sorted lists rather than sorting a single large, unsorted one.
How Merge Sort Works
-
Divide Phase: Divide the unsorted array into smaller sub-arrays until each sub-array has only one element.
-
Conquer Phase: Recursively merge adjacent sub-arrays to produce new sorted sub-arrays until there is only one sorted array remaining.
-
Merge Phase: Repeatedly merge sorted sub-arrays to generate larger, more sorted sub-arrays until the entire array is sorted.
Okay, now we’re down to the smallest possible subproblem: eight lists, and each has one, sorted item within it. Now, we just need to merge two lists together. We’ll merge each sorted list together with its neighbor. When we merge them, we’ll check the first item in each list, and combine the two lists together so that every element is in the correct, sorted order.
Easy-peasy! We got this.
Great! Once we started merging two lists together, we didn’t have to think too much more when it came to merging those two sorted sublists, did we? We used the same technique to merge lists with four items as we did when we merged lists with only one item.
A mergeSort function ultimately has two functions inside of it:
-
a merge function, which actually combines two lists together and sorts them in the correct order
-
and a mergeSort function, which will continue to split the input array again and again, recursively, and will also call merge again and again, recursively.
Pseudocode
Advantages
- Offers consistent, optimal performance across different datasets.
- Preserves stability as equal elements retain their original order.
- Suitable for sorting linked lists.
Disadvantages
- Requires additional memory space for merging.
- Slower for small datasets compared to other sorting algorithms like Insertion Sort or Bubble Sort.