Page 611 - AP Computer Science A, 7th edition
P. 611
123456
(E) 1 3 5 7 9 11 1 3 5 7 9 11
Questions 39 and 40 refer to the following information.
Consider an array arr that is sorted in increasing order, and method findMost given below. Method findMost is intended to find the value in the array that occurs most often. If every value occurs exactly once, findMost should return –1. If there is more than one value that occurs the most, findMost should return any one of those. For example, if arr contains the values [1,5,7,7,10], findMost should return 7. If arr contains [2,2,2,7,8,8,9,9,9],
findMost s hould ret urn 2 or findMost should return –1.
9. If arr c ont ains [1,2,7,8], arr sorted in increasing
Line 1:
Line 2:
Line 3:
Line 4:
Line 5:
Line 6:
Line 7:
Line 8:
Line 9:
Line 10:
Line 11:
Line 12:
/∗ ∗ Precondition: order.
∗/
public static int findMost(int[] arr) {
int index = 0;
int count = 1;
int maxCountSoFar = 1;
int mostSoFar = arr[0];
while (index < arr.length – 1)
{
while (index < arr.length – 1 &&
arr[index] == arr[index + 1])