Merge sort is a sorting algorithm that uses a divide and conquer approach. It divides an array into halves, recursively sorts the halves, and then merges the sorted halves into a single sorted array. The key steps are dividing, conquering by recursively sorting subarrays, and combining the sorted subarrays through a merging process. It has advantages of being a stable sort and having no worst-case scenario, though it requires more memory than other sorts.
Merge Sort
Merge sortis based on the divide-and-conquer paradigm.
To sort A[p .. r]:
1. Divide Step
If a given array A has zero or one element, simply return; it is already sorted.
Otherwise, split A[p .. r] into two subarrays A[p .. q] and A[q + 1 .. r], each
containing about half of the elements of A[p .. r]. That is, q is the halfway point of
A[p .. r].
2. Conquer Step
Conquer by recursively sorting the two subarrays A[p .. q] and A[q + 1 .. r].
3.
3. Combine Step
Combinethe elements back in A[p .. r] by merging the two sorted subarrays A[p ..
q] and A[q + 1 .. r] into a sorted sequence. To accomplish this step, we will define a
procedure MERGE (A, p, q, r).
Note that the recursion bottoms out when the subarray has just one element, so
that it is trivially sorted.
4.
The following figuretells to continue expanding
until the problem sizes get down to 1.
5.
a problem ofsize n
subproblem 1
of size n/2
subproblem 2
of size n/2
a solution to
subproblem 1
a solution to
subproblem 2
a solution to
the original problem
Pros:
It is astable sort, and there is no worst-case scenario.
It is faster, the temp array holds the resulting array until both left and right
sides are merged into the temp array, then the temp array is appended
over the input array.
It is used in tape drives to sort data - its good with parallel processing.
18.
Cons:
The memory requirementis doubled.
Takes longer to merge because if the next element is in the right side then
all of the elements must be moved down.