Java Reference
In-Depth Information
If we wanted to print the results in alphabetical order, we could do so by calling selectionSort (Section 2.13)
with this statement:
selectionSort(candidate, 1, MaxCandidates);
We could achieve the same result by calling insertionSort (Section 2.13) like this:
insertionSort(candidate, 1, MaxCandidates);
But suppose we wanted to print the names of the candidates in descending order by number of votes received,
that is, with the winning candidate(s) first. To do this, the object array candidate must be sorted in descending order
using the numVotes field to control the sorting. This could be done by the following call where sortByVote uses an
insertion sort ( any sort will do) and is written using the formal parameter list :
sortByVote(candidate, 1, MaxCandidates);
We can write sortByVote as follows:
public static void sortByVote(Person[] list, int lo, int hi) {
//sort list[lo] to list[hi] in descending order by numVotes
for (int h = lo + 1; h <= hi; h++) {
Person hold = list[h];
int k = h - 1; //start comparing with previous item
while (k >= lo && hold.numVotes > list[k].numVotes) {
list[k + 1] = list[k];
--k;
}
list[k + 1] = hold;
} //end for
} //end sortByVote
Suppose we add sortByVote to Program P2.5, and we insert this statement:
sortByVote(candidate, 1, MaxCandidates);
just before this one:
printResults(out, candidate, MaxCandidates, count);
If we run the program with the same data as before, it will produce the following output. The candidates are
printed with the highest score first and the lowest score last.
Search WWH ::




Custom Search