The following applet is a working version of MergeSort. It sorts an array of sixteen bars. Click the Go button and watch it sort the blue bars into green bars.

To sort the left half of the array, the program calls itself recursively, passing the left half of the bars down to a new activation of MergeSort. This happens repeatedly until we have an array of only one element. As noted earlier, one-element arrays are already sorted. Bars in sorted arrays are coloured green (or light grey on a black and white screen).

When the left half of an array is sorted, we sort the right half.

Once the two halves of an array have been sorted by recursive calls,
MergeSort *merges* the two sorted halves into a sorted whole.
This is done by examining and comparing the smallest remaining bar in each
of the sorted halves. The two bars being compared are coloured
red (or medium grey). The smaller of these two bars turns green and
is moved up and
tacked onto the right end of the parent array.

When one of the two subarrays becomes empty, the remaining bars in the other subarray are copied in order into the parent array. No comparisons need to be made.

That describes the workings of MergeSort. I suggest you go back, click on the ``Load input'' button, then click on the ``Go'' button, and adjust the speed slider so that you can see the comparisons being made. Then come back.

I have used strict inequality because we have actually overestimated the number of comparisons required for merging by 1 at each level. (To tell you the truth, it's really because I couldn't find a nice-looking less-than-or-equal-to sign that would fit in that space!)

If you are adventurous, you can type in your own values for the heights of the bars by first clicking on the text box next to the input choice menu, and then typing. Actually, you can specify any set of numbers you like, but only the first 16 will be looked at. Even then, the program doesn't use the absolute values as bar heights, but only their relative ordering. If you type in fewer than 16 numbers, then the last number is repeated. For example, to see what MergeSort does when when all the inputs are the same, type in just a single 1 in the text box, then load the input, and click on ``Go''.

If you are adventurous but lazy, then you can just click on the button labelled ``Shuffle now''. This randomly rearranges the numbers in the text box. For interesting results, select the ``Ascending'' input and then shuffle it a few times.