AP Computer Science A · Topic 7.5
Searching Practice
Part of ArrayList.
Practice questions
11
Sample questions
5 of 11 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
ArrayList<String> list = new ArrayList<>(); list.add("cat"); list.add("dog"); list.add("bird"); boolean found = false; for (String s : list) { if (s.equals("dog")) found = true; } System.out.println(found);What is printed?
- Acheck_circle
true
- B
false
- C
dog
- D
1
Why
"dog" is in the list, so the if statement sets found to true.
- A
Sample 2difficulty 2/5
int[] a = {2, 5, 2, 7, 2, 8}; int count = 0; for (int x : a) { if (x == 2) count++; }What is count?
- A
4
- B
2
- Ccheck_circle
3
- D
1
Why
The value 2 appears at indices 0, 2, and 4, so count is 3.
- A
Sample 3difficulty 2/5
// linear search on array of size nWhat is the worst-case time complexity?
- A
O(n^2)
- B
O(log n)
- Ccheck_circle
O(n)
- D
O(1)
Why
Linear search may inspect every element, giving O(n) worst case.
- A
Sample 4difficulty 2/5
int[] a = {3, 7, 1, 9, 4}; int target = 100; int idx = -1; for (int i = 0; i < a.length; i++) { if (a[i] == target) { idx = i; break; } }What is idx after the loop?
- Acheck_circle
-1
- B
4
- C
5
- D
0
Why
Target 100 is not in the array, so idx remains its initial value of -1.
- A
Sample 5difficulty 2/5
int[] a = {1, 2, 3, 4}; int target = 99; int idx = -1; for (int i = 0; i < a.length; i++) { if (a[i] == target) { idx = i; } } System.out.println(idx);What is printed?
- Acheck_circle
-1
- B
4
- C
0
- D
ArrayIndexOutOfBoundsException
Why
99 is not in the array, so idx remains its initial value of -1. The convention -1 indicates "not found".
- A