8.4. Looping From Back to Front

You don’t have to loop through an array from the front to the back. You can loop by starting at the back of the array and move toward the front during each time through the loop. This can be handy when you are looping through a sorted array and want to find the index of the last number that is less than some given number as shown in the method getIndexLastSmaller below. Notice that the method returns -1 if there is no number in the array that is smaller than the given number. Why does this work?

Note

Notice that if the array is a field of the ArrayWorker class you must create an ArrayWorker object in the main method. You don’t have to pass the array to the getIndexLastSmaller method like you do if the method is static. The object already has the array as a field and any object method has access to it.

You can step through execution of this code using the Java Visualizer by clicking on the following link1.

    7-4-1: Given the following code segment what will be returned when you execute: getIndexLastSmaller(-13);

    private int[ ] values = {-20, -15, 2, 8, 16, 33};
    
    public int getIndexLastSmaller(int compare)
    {
       for (int i = values.length - 1; i >=0; i--)
       {
          if (values[i] < compare) return i;
       }
       return -1; // to show none found
    }
    
  • -1
  • The method will only return -1 if no value in the array is less than the passed value.
  • -15
  • The method returns the index of the first item in the array that is less than the value, not the value.
  • 1
  • Since the method loops from the back towards the front -15 is the last value in the array that is less than -13 and it is at index 1.
  • You will get an out of bounds error.
  • No, the method correctly starts the index at values.length - 1 and continues as long as i is greater than or equal to 0.

    7-4-2: Given the following code segment what will be returned when you execute: getIndexLastSmaller(7);

    private int[ ] values = {-20, -15, 2, 8, 16, 33};
    
    public int getIndexLastSmaller(int compare)
    {
       for (int i = values.length; i >=0; i--)
       {
          if (values[i] < compare) return i;
       }
       return -1; // to show none found
    }
    
  • -1
  • The method will only return -1 if no value in the array is less than the passed value.
  • 1
  • Check the starting index. Is it correct?
  • 2
  • Check the starting index. Is it correct?
  • You will get an out of bounds error.
  • You can not start the index at the length of the array. You must start at the length of the array minus one. This is a common mistake.
Next Section - 8.5. Looping through Part of an Array