Chapter 13 - Arrays - continuedWe have seen how to create and initialize arrays and we have done a few operations on them. We still need a little more practice so let’s consider some more simple operations. In the following examples, we will always assume that the same of the array is array and we will refer to the length of the array as array.length and assume that it is an array of integers.
Let’s start with something simple again.
Zeroing out the elements in an array:
for ( int i = 0 ; i < array.length ; i++)Multiplying all of the elements of the array together:
array[ i ] = 0;product = 1;Adding up only the odd numbers that are in the array:
for (int index = 0 ; index < array.length ; index++ )
product = product * array[ index ];oddSum = 0;
for (int j = 0 ; j < array.length ; j++ )
if( j % 2 == 1)
sum = sum + array[ j ];
Searching an arrayOne of the big operations that are done with arrays is to look through them (search them) to see if a particular element is in the array. For our purposes we will write this search routine as a method. The method will search the array for a particular value and return the index of the array if that value was found. If the value cannot be found, the method will return a -1 (since -1 is an invalid array index).
public int searchForValue ( int [] array, int valueToSearchFor){int answer;
answer = -1; // assume we do not find itfor ( int s = 0 ; s < array.length ; s++)
if ( array [ s ] == valueToSearchFor){
answer = s;
break;
}
return answer;
}
Methods can be written to search for just about anything. In our example on an array of integers, we could just search for the smallest element in the array:public int searchForSmallest( int [] array ){int smallest;
// start out by assuming the smallest element is in the first position
smallest = array[ 0 ];// now look through the rest and reset "smallest" if necessary
for ( int index = 1 ; index < array.length ; index++ )
if (array[ index ] < smallest )
smallest = array[ index ];return answer;
}
How would you change the above method to search for the largest element?This should be easy.
Here is a more difficult question. How would you write a method that searches for and finds the next to the largest element?
A Tricky Example
Here’s a tricky little example. Suppose you want to reverse the arrangement of the elements in the array, so that whatever was in the first position gets placed in the last position, the element in the second position gets placed in the next to the last, etc.
Original: 5 7 4 20 11
Reversed: 11 20 4 7 5
Here is how you do it. First find out what the middle position is. You can do this by looking at array.length/2. For example if the array has 5 elements like the one above then array.length/2 = 5/2 = 2 and the number 4 above is in position where its index is 2. Now write a loop that swaps things. Remember how to swap?
int temp;
for ( int index = 0 ; index <= array.length/2 ; index++){
temp = array [ index ];
array [ index ] = array[ array.length - 1 - index ];
array[ array.length - 1 - index ] = temp;
}
That was tricky. A few questions arise. First of all, why all the tricky indexing for the one array element? Secondly, would this work if there were an even number of elements in the array? Remember we were working on an array of 5 elements. Thirdly, why does the loop stop at array.length/2 rather than going all the way to array.length as we did in the past?Arrays of objects
After a while, dealing with arrays that contain only integers can get pretty boring. Just remember that arrays can contain ANYTHING, as long as all of the array elements contain the same type of elements.
For example we could create a class that describes students:
class Student {
String firstName;
String lastName;
int telephoneNumber;
float gradePointAverage;
int studentID;
}
and then create an array of students for the whole college like this:Student[ ] collegeStudents = new Student[1200];In order to reference one of these items we need to use the dot (.) operator again. Suppose we wanted to put a student’s data somewhere in the array, say at index 133. We could write:collegeStudent[133].firstName = "Sally";You can even have arrays of GUI elements like:
collegeStudent[133].lastName = "Fields";
collegeStudent[133].telephoneNumber = 7248525555;
etc.TextField [ ] myInputs = new TextField[ 5 ];and you can call a method on one of these elements easily tooanInput = myInputs[ 2 ].getText( );Bars and ChartsYour textbook covers how to draw bars and charts. This is another excellent way in which arrays are used. You should study the sample method on page 250 in the book, but I am not going to cover this section in class.
Sorting
I do want to say a few words about sorting. This is part of the assignment I gave you. There are many many different algorithms (methods) that you can write to sort the elements of an array. Some are simple (but pretty slow); some are very complicated (yet fast). The hint that is in problem 13.15 in your text gives you a method that is slow, but fairly easy to write. It says
"Find the smallest number in the array. Swap it into the first item in the array. Now the first item in the array is in the right place. Leave this item alone and repeat the operation on the remainder of the array (everything except the first item). Repeat, carrying out this operation on a smaller and smaller array until the complete array is in order."Now what does all of that mean? Let’s look at an example. Suppose our array looks like this:Element: 22 13 5 32 11 8
Index: 0 1 2 3 4 5
Step 0: Execute a for loop (start at index 0) to find the smallest ( 5 at index 2)
Swap the 5 and the 225 13 22 32 11 8
Now the 5 is in the correct position.
Step 1: Execute a for loop (start at index 1) to find the smallest ( 8 at index 5)
Swap the 8 and the 135 8 22 32 11 13
Now the 8 is in the correct position.
Step 2: Execute a for loop (start at index 2) to find the smallest ( 11 at index 4)
Swap the 11 and the 225 8 11 32 22 13
Now the 11 is in the correct position.
Step 3: Execute a for loop (start at index 3) to find the smallest ( 13 at index 5)
Swap the 13 and the 325 8 11 13 22 32
Now the 11 is in the correct position.
Now you as a human can see that the array is ordered at this point, but the computer cannot. It still needs to go through the process one more time to make sure everything is ok.
Step 4: Execute a for loop (start at index 4) to find the smallest ( 22 at index 4)
Swap the 22 and the 225 8 11 13 22 32
Now the 11 is in the correct position.
I know this last one seems silly, but it works and it is necessary because this method has to work on ANY array, not just the one we were using for our example.
Now notice how I numbered the steps 0, 1, 2, 3, 4. This should give you a hint that there should be an "outer" loop that goes from 0 to n-2 if there are n elements in the array. Also notice that each step specifies that the array be searched starting at the same number as the step number and going up through n-1, the last element of the array, an "inner" loop. This should lead you to a nested for loop construction that looks something like this:
for ( int i = 0 ; i < array.length-1 ; i++ )for ( int j = i ; j < array.length ; j++)
I will not give the details of what to do inside of these loops, but this discussion should start you off.
-from Java for Students, by Bell and Parr; examples by Dr. Leipold