Page 428 - Introduction to Programming with Java: A Problem Solving Approach
P. 428
394 Chapter 10 Arrays and ArrayLists
list list
(original)
0 -3 -3
12
2
(sorted)
-3
2
5
20
10
3
4
5
10
-3
20
2
10
-3
2
5
20
2
5
20
10
5
10
20
Figure 10.14 Example execution of the Selection Sort algorithm
method, you can easily call it from any program that needs to sort a list of numbers—just prefix the method call with class name dot.
See the Sort class in Figure 10.15. Note how the sort method body mimics the pseudocode very closely because the sort method uses top-down design. Rather than include the search-for-the-smallest-value code within the sort method, the sort method calls the indexOfNextSmallest helper method. Rather than include the element-swapping code within the sort method, the sort method calls the swap helper method. The only substantive difference between the sort method and the sort algorithm is that the sort method’s for loop stops iAterpatianggonoe elemPeDnt bFeforeEthne bhotatomnocf teherarray. That’s because there’s no need to perform a search when you’re at the last element (you already know that the last element is the minimum value for the remainder of the list). We didn’t worry about such efficiency details with the algo- rithm because algorithms are more about basic logic rather than off-by-one details.
Passing Arrays as Arguments
Figure 10.16 contains a driver for Figure 10.15’s Sort class. Most of the code is fairly straightforward, but please take note of the studentIds argument in the Sort.sort method call. That’s an example of passing an array to a method. An array is an object, and as such, studentIds is a reference to an array object. As you may recall from the “Passing References as Arguments” section in Chapter 7, a refer- ence argument (in a method call) and its corresponding reference parameter (in a method heading) point to the same object. So if you update the reference parameter’s object from within the method, you simul- taneously update the reference argument’s object in the calling module. Applying that thinking to the Sort program, when you pass the studentIds reference to the sort method and sort the array there, there’s no need to return the updated (sorted) array with a return statement. That’s because the studentIds reference points to the same array object that is sorted within the sort method. Thus, we do not include a return statement in the sort method, and the method works just fine.
Sorting with a Java API Method
Check for efficient API methods.
When an array has more than about 20 elements, it’s better to use an algorithm that’s more efficient than the relatively simple Selection Sort algorithm just described. And sure enough, the Java API has a sorting method that uses a more efficient sorting algorithm. It’s the sort method in the Arrays class.