Chapter 8: Collections: Arrays Searching and Sorting Arrays as Arguments
Aggregate Data Types – re-visited Some objects are made up of other objects – e.g. a computer system. Aggregation is sometimes described as a “has-a” relationship. For instance, a car has 4 wheels. In software, we define an aggregate data type consisting of one or more scalar data type objects
Run-Time Dimensioning The size of an array can also be entered interactively at run time An entered value can be used to allocate space for an array using the new operator
public static void main(String[] args) { int i, numgrades; int grade[]; // declare the array String s1; s1 = JOptionPane.showInputDialog("Enter the number of grades” + “ to be processed: "); numgrades = Integer.parseInt(s1); grade = new int[numgrades]; // allocate the array
The Arrays Class: Searching and Sorting Java-provided class Distinct from the Array class we have been implementing Called helper class because it provides a number of extremely useful methods that can be a great help in processing arrays Contains methods for: Sorting an array Searching a sorted array for a particular item
The sort() and binarySearch() Methods sort() method Arranges elements of array into ascending (increasing) order Uses modified quicksort algorithm – we’ll look at this in more detail in 8.9 Only works for: Primitive data types Strings
The sort() and binarySearch() Methods (continued) Searches array for a specified value Requires a sorted array Returns: Item index if found Negative number if not found
Search & Sort Generally the sort( ) method is called immediately before the binarySearch( ) method. Use either import java.util.*; or import java.util.Arrays; Example:
String s1; int i, numels; int variousNums[]; int item, location; // set up the basic input stream BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter the number of array values: "); s1 = br.readLine(); numels = Integer.parseInt(s1); // allocate the array variousNums = new int[numels]; // read the array values for (i = 0; i < numels; i++) { System.out.print("Enter element " + (i+1) + ": "); s1 = br.readLine();_ variousNums[i] = Integer.parseInt(s1); }
// sort the array Arrays // sort the array Arrays.sort(variousNums); // display the sorted array System.out.print("The values in sorted order are:"); for (i = 0; i < numels; i++) System.out.print(" " + variousNums[i]); // now locate a desired element System.out.print("\n\nEnter the item you are searching for: "); s1 = br.readLine(); item = Integer.parseInt(s1); location = Arrays.binarySearch(variousNums, item); if (location > 0) System.out.println("This item is at location " + (location + 1) + " in the sorted array."); else System.out.println("This item is not in the list."); } }
Arrays as Arguments Individual array elements are passed to a called method in the same manner as individual scalar variables Passed by value – i.e. method receives a copy of the stored value, can manipulate it, but cannot directly change the value in the original array. e.g. findMax (number[5], number[7])
Passing an entire array A complete array can be passed by reference The called method may change items in the original array double salary [ ] = new double [5]; …. findMax(salary); Must alert the method that an array is coming in header line: double findMax (double vals [ ])
public class ArrayArgument { public static void main(String[] args) { int nums[ ] = {2, 18, 1, 27, 16}; // the call is made here System.out.println("The maximum value is " + findMaximum(nums)); } // this is the called method used to find the maximum value // stored in an array of integers public static int findMaximum(int vals[]) { int i, max = vals[0]; for (i = 1; i < vals.length; i++) if (max < vals[i]) max = vals[i]; return max; } }
figure 8.14 on page 418 illustrates that the method references the original array.
Class Exercise p. 416 # 1, 2 p. 420 # 1, 3, 5, 7