Q. Sorting seems like a toy problem. Aren’t many of the other things that we do with
computers much more interesting?
A. Perhaps, but many of those interesting things are made possible by fast sorting algorithms.
You will find many examples in Section 2.5 and throughout the rest of the
book. Sorting is worth studying now because the problem is easy to understand, and
you can appreciate the ingenuity behind the faster algorithms.
Q. Why so many sorting algorithms?
A. One reason is that the performance of many algorithms depends on the input values,
so different algorithms might be appropriate for different applications having different
kinds of input. For example, insertion sort is the method of choice for partially
sorted or tiny arrays. Other constraints, such as space and treatment of equal keys, also
come into play. We will revisit this question in Section 2.5.
Q. Why bother using the tiny helper methods less() and exch()?
A. They are basic abstract operations needed by any sort algorithm, and the code is
easier to understand in terms of these abstractions. Moreover, they make the code directly
portable to other settings. For example, much of the code in Algorithms 2.1
and 2.2 is legal code in several other programming languages. Even in Java, we can use
this code as the basis for sorting primitive types (which are not Comparable): simply
implement less() with the code v < w.
Q. When I run SortCompare, I get different values each time that I run it (and those
are different from the values in the book). Why?
A. For starters, you have a different computer from the one we used, not to mention
a different operating system, Java runtime, and so forth. All of these differences might
lead to slight differences in the machine code for the algorithms. Differences each time
that you run it on your computer might be due to other applications that you are running
or various other conditions. Running a very large number of trials should dampen
the effect. The lesson is that small differences in algorithm performance are difficult to
notice nowadays. That is a primary reason that we focus on large ones!