Professional Documents
Culture Documents
Note that the recursion bottoms out when the subarray has just
one element, so that it is trivially sorted.
Merging
What remains is the MERGE procedure. The following is the
input and output of the MERGE procedure.
INPUT: Array A and indices p, q, r such that p q r
and subarray A[p .. q] is sorted and subarray A[q +
1 .. r] is sorted. By restrictions on p, q, r, neither
subarray is empty.
OUTPUT: The two subarrays are merged into a single
sorted subarray in A[p .. r].
We implement it so that it takes (n) time, where n = r p +
1, which is the number of elements being merged.
Running Time
The first two for loops (that is, the loop in line 4 and the loop
in line 6) take (n1 + n2) = (n) time. The last for loop (that
is, the loop in line 12) makes n iterations, each taking constant
time, for (n) time. Therefore, the total running time is (n).
Recursion Tree
We can understand how to solve the merge-sort recurrence
without the master theorem. There is a drawing of recursion
tree on page 35 in CLRS, which shows successive expansions
of the recurrence.
The following figure (Figure 2.5b in CLRS) shows that for the
original problem, we have a cost of cn, plus the two
subproblems, each costing T (n/2).
Mathematical Induction
We use induction on the size of a given subproblem n.
Base case: n = 1
Implies that there is 1 level, and lg 1 + 1 = 0 + 1 = 1.
Inductive Step
Our inductive hypothesis is that a tree for a problem
size of 2i has lg 2i + 1 = i +1 levels. Because we
assume that the problem size is a power of 2, the next
problem size up after 2i is 2i + 1. A tree for a problem
size of 2i + 1 has one more level than the size-2i tree
(n lg n)
which is the desired result.
Implementation
int mid;
if (right > left)
{
void merge(int numbers[], int temp[], int left, int mid, int
right)
temp[tmp_pos] = numbers[left];
tmp_pos = tmp_pos + 1;
left = left +1;
}
else
{
temp[tmp_pos] = numbers[mid];
tmp_pos = tmp_pos + 1;
mid = mid + 1;
}
}
temp[tmp_pos] = numbers[left];
left = left + 1;
tmp_pos = tmp_pos + 1;
}
temp[tmp_pos] = numbers[mid];
mid = mid + 1;
tmp_pos = tmp_pos + 1;
}
numbers[right] = temp[right];
right = right - 1;
}
}