A step-by-step illustration of Merge sort to help you walk through a series of operations. Illustration is accompanied by actual code with bold line indicating the current operation.
3. Merge function
This function does the most of the heavy lifting,
so we look at it first, then see it in the context of
Merge Sort algorithm
4. Merge Function
for (int i = begin; i <= last; i++) {
helper[i] = array[i];
}
Part #1: prepare helper
int left = begin;
int right = middle + 1;
int storeIndex = begin;
while (left <= middle
if (helper[left] <=
array[storeIndex]
left++;
} else {
array[storeIndex]
right++;
}
&& right <= last) {
helper[right]) {
= helper[left];
Part #2: pick smaller and
copy to the target
= helper[right];
storeIndex++;
}
int remainder = middle - left;
for (int i = 0; i <= remainder; i++) {
array[storeIndex + i] = helper[left + i];
}
Part #3: copy any
remainder from left
(right not necessary)
46. Already sorted
(unchanged but sorted)
Call Stack #1
Call Stack #0
middle
begin
last
[0]
[1]
[2]
[3]
5
7
3
2
if (begin >= last) {
return;
}
int middle = (begin + last) / 2;
MergeSort(array, helper, begin, middle);
MergeSort(array, helper, middle + 1, last);
Merge(array, helper, begin, middle, last);
(implicit return at the end of function)
47. Merge & Sort the
right sub-array next
Call Stack #0
begin
last
middle
[0]
[1]
[2]
[3]
5
7
3
2
if (begin >= last) {
return;
}
int middle = (begin + last) / 2;
MergeSort(array, helper, begin, middle);
MergeSort(array, helper, middle + 1, last);
Merge(array, helper, begin, middle, last);
48. Walkthrough ends here.
The right sub-array is processed the
same way as the left sub-array.
After that, Merge is called with two
already-sorted sub-arrays
Call Stack #1
Call Stack #0
begin
last
[0]
[1]
[2]
[3]
5
7
3
2
if (begin >= last) {
return;
}
int middle = (begin + last) / 2;
MergeSort(array, helper, begin, middle);
MergeSort(array, helper, middle + 1, last);
Merge(array, helper, begin, middle, last);