Java Reference
In-Depth Information
swap(list, h, getSmallest(list, h, hi));
} //end selectionSort
public static int getSmallest(Person[] list, int lo, int hi) {
// return the position of the 'smallest' name from list[lo] to list[hi]
int small = lo;
for (int h = lo + 1; h <= hi; h++)
if (list[h].name.compareToIgnoreCase(list[small].name) < 0) small = h;
return small;
} //end getSmallest
public static void swap(Person[] list, int h, int k) {
// swaps list[h] with list[k]
Person hold = list[h];
list[h] = list[k];
list[k] = hold;
} //end swap
In getSmallest , we compare the name field of one array element with the name field of another array element.
We could sort the array person from Program P2.1 with the following call:
selectionSort(person, 0, person.length - 1);
We could then print the array person with this:
for (int h = 0; h < person.length; h++) person[h].printPerson();
where printPerson is defined in class Person as follows:
void printPerson() {
System.out.printf("%s %d %c\n", name, age, gender);
}
For the array in Program P2.3, this will print the following output:
Abel 30 M
Bert 32 M
Gary 25 M
Inga 21 F
Mary 27 F
Nora 19 F
Olga 36 F
We can also sort an array of Person objects using insertion sort as follows:
public static void insertionSort(Person[] list, int lo, int hi) {
//sort list[lo] to list[hi] in ascending order by name
for (int h = lo + 1; h <= hi; h++) {
Search WWH ::




Custom Search