Understanding merge sort algorithm


The strategy from the earlier librarian and books example could be used to create an algorithm. To explain this algorithm, we will take an array as an input list, but the same algorithm can be applied to any list data structure.

Algorithm

The merge sort algorithm begins by dividing the input array into two roughly equal-sized subarrays. This division continues recursively, breaking the array into smaller and smaller segments, until each subarray contains only a single element. At this stage, each subarray is trivially sorted, as a single element is inherently in order.

Recursively divide the array until all subarrays have one element

Once the array has been divided into individual elements, the algorithm starts the merging process. It combines pairs of subarrays by comparing elements and arranging them in sorted order. This step ensures that each merged array maintains the correct order.

Merge individual elements to form sorted subarrays

The merging continues recursively, gradually combining these sorted subarrays into increasingly larger sections, until the entire array is merged into a single, fully sorted array.

Merge sorted subarrays to form larger sorted subarrays

Liking the course? Check our discounted plans to continue learning.