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?
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];
}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];
}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];
}
- I only
- II only
- III only
- II and III only
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.