(Latest Revision: 2015/09/19)
Comparing Sorts Program Help and Hints
- Counting comparisons done in boolean expressions:
You can take code like this:
if (theArray[currentIndex] > theArray[indexSoFar])
and turn it into code like this:
if (++c_count && (theArray[currentIndex] > theArray[indexSoFar]))
The expression "++c_count" takes care of incrementing the
counter that tracks the number of comparisons. If you initialize
counters correctly, the addition of expressions such as
"++c_count" will not change the logic of the program.
(Verify.)
Notice that order is important here. It does not work to put
"&& ++c_count" at the end of the original expression. (Why
not?) Also it doesn't work right if you put "c_count++ &&"
at the beginning of the original expression. (Why not?) If you
are unsure of the answers to either of the foregoing questions, then
review material about how Boolean expressions are evaluated in C++,
and details about the difference between the values returned by ++x
and x++.
- Flushing Output: Use code like this:
cout << "mergesort starting ... " ;
cout.flush() ;
mergesort(A, 0, howMany-1, cmpCount, mvCount) ;
cout << "done" << endl ;
to help the user see when the program starts and finishes each sort.
If you don't use something like
cout.flush()
after
cout << "mergesort starting ... " ;
then the output may be buffered - which means you won't see this
output on the screen
"mergesort starting ..."
until after the mergesort is completed!
The endl in this statement
cout << "done" << endl ;
prints a newline character AND flushes the output, so you don't
need to add a
cout.flush()
after
cout << "done" << endl ;
- Counter Data Types Big Enough For Big Numbers:
It may be a good idea to make your counters unsigned long int. This
will give you a little extra margin in case you come close to
overflowing your counters. For example, you could declare your
counters this way:
unsigned long int cmpCount, mvCount ;
Remember, when writing your code, to (re) initialize your counters
when you start at new sort. It's an elementary, but common, mistake
to start a new sort with a counter that has not been (re) initialized.
- Sorting a Fresh Copy of the Original List Each Time:
It is also an elementary observation, but one easily overlooked,
that after you sort the list, it's not the original list any more -
it has been sorted. So in this program, which is required to compare
the performance of different sorting algorithms on the same input, you
must arrange to give a "fresh" copy of the original input to each sorting
algorithm. The usual way to do this is to keep one version of the list
as an original and to make a new copy of the original each time you
call for another sort. In C++, it's usually necessary to copy arrays
by copying each slot, one at a time. Typically programmers do this
with a for-loop.