Merge Sort

chevron-rightThe divide-and-conquer approachhashtag

Many useful algorithms are recursive in structure: to solve a given problem, they call themselves recursively one or more times to deal with closely related sub-problems.

These algorithms typically follow a divide-and-conquer approach: they break the problem into several subproblems that are similar to the original prob- lem but smaller in size, solve the subproblems recursively, and then combine these solutions to create a solution to the original problem.

Divide the problem into a number of subproblems that are smaller instances of the same problem.

Conquer the subproblems by solving them recursively. If the subproblem sizes are small enough, however, just solve the subproblems in a straightforward manner.

Combine the solutions to the subproblems into the solution for the original problem.

  • Divide: Divide the n-element sequence to be sorted into two subsequences of n=2 elements each.

  • Conquer: Sort the two subsequences recursively using merge sort.

  • Combine: Merge the two sorted subsequences to produce the sorted answer.

MERGE_SORT: O(nlogn)

MERGE-SORT(A,p,r)
  if p < r               // Check for base case: O(1)
     q = floor((p+r)/2)  // Divide: O(1)
     MERGE-SORT(A,p,q)   // Conquer: T(n/2)
     MERGE-SORT(A,q+1,r) // Conquer: T(n/2)
     MERGE(A,p,q,r)      // Combine: O(n)

Running time:

T(n)={Θ(1) if n=12T(n/2)+Θ(n) otherwise T(n)=\left\{\begin{array}{cc}\Theta(1) & \text { if } n=1 \\ 2 T(n / 2)+\Theta(n) & \text { otherwise }\end{array}\right.

Therefore, T(n)T(n) is Θ(nlogn)\Theta(nlogn)

MERGE: O(n)

where n = r - p + 1 is the total number of elements being merged.

Example: Remove Duplicates

Pseudocode: This algorithm sorts the list of names, then scans through the sorted list to find unique names and move them to the front of the list.

Last updated