CS 46A - Lecture 21

Cover page image

Pre-class reading

Common Array Algorithm: Locating the Position of an Element

Lecture 21 Clicker Question 1

The algorithm above locates the first match. What if you want to get all matching values?

  1. You can collect all matching values in an ArrayList<Double>
  2. You can collect the positions of all matching values in an int[] array
  3. You can supply a function
    int findFirst(double[] values, double limit, int startPosition)

    and call it repeatedly

  4. All of the above will work

Common Array Algorithm: Removing an Element

Common Array Algorithm: Removing an Element

Common Array Algorithm: Inserting an Element

Common Array Algorithm: Inserting an Element

Lecture 21 Clicker Question 2

Consider this variation of the insertion algorithm.

if (valuesSize < values.length) 
{ 
   for (int i = pos + 1; i < valuesSize; i++) 
   { 
      values[i] = values[i - 1]; 
   } 
   values[pos] = newElement; 
   valuesSize++; 
}

What is the contents of values after the loop when pos is  3, newElement is 10, valuesSize is 6, and before the loop, values is

1 4 9 16 25 36 0 0 0 0
  1. 1 4 9 10 16 25 36 0 0 0
  2. 1 4 10 9 16 25 36 0 0 0
  3. 1 4 9 10 16 16 16 0 0 0
  4. Something else

Common Array Algorithm: Copying an Array

Common Array Algorithm: Growing an Array

Common Array Algorithm: Growing an Array

Common Array Algorithm: Printing Element Separators

Lecture 21 Clicker Question 3

The following replacement has been suggested for the algorithm that prints element separators:

System.out.print(names.get(0)); 
for (int i = 1; i < names.size(); i++)
   System.out.print(" | " + names.get(i));

What is problematic about this suggestion?

  1. Nothing—it works perfectly
  2. It prints one separator too many
  3. It prints one separator too few
  4. It can cause an index out of bounds exception

Two-Dimensional Arrays

Traversing Two-Dimensional Arrays