Learn AP Comp Sci

Problem of the Day

Friday, December 12, 2025


Problem:

Which of the following methods smallest correctly identify the smallest value in an array of int values?


  1. public static int smallest(int[] arr)
    {
    int i = 0;
    for (int j = 1; j < arr.length + 1; j++)
    if (arr[j] < arr[i])
    i = j;
    return arr[i];
    }

  2. public static int smallest(int[] arr)
    {
    int i = 0;
    for (int j = 1; j < arr.length; j++)
    if (arr[j] < arr[i])
    i = j;
    return arr[i];
    }

  3. public static int smallest(int[] arr)
    {
    for (int j = arr.length - 1; j > 0; j--)
    if (arr[j] < arr[j - 1])
    {
    int t = arr[j];
    arr[j] = arr[j - 1];
    arr[j - 1] = t;
    }
    return arr[0];
    }
  1. I only
  2. II only
  3. III only
  4. II and III only

Show solution:

The correct answer is d. Choice I produces a bounds error, while II and III both identify the smallest element in the array. Although both of these methods work, choice II is the better strategy—the third method performs a lot of element-switching as it moves the smallest element to the first position in the array.