Advanced Topics MCQ

Code Tracing: Sorting, Searching, and Efficiency

Practice mode shows one question at a time and lets students check each answer before moving on.

All AT CS Tests

For practice use only.

Code Tracing: Sorting, Searching, and Efficiency

Code Tracing: Sorting, Searching, and Efficiency with immediate answer checks and explanations for Advanced Topics in Computer Science.

Question 1 of 25

Answered 0 of 25

Choose one answer.

Trace binary search and count how many comparisons are made. What is printed?

public class BinarySearchTrace
{
    public static void main(String[] args)
    {
        int[] a = {3, 8, 12, 18, 24, 31, 40};
        int target = 12;
        int lo = 0, hi = a.length - 1, checks = 0, found = -1;
        while (lo <= hi)
        {
            checks++;
            int mid = (lo + hi) / 2;
            if (a[mid] == target) { found = mid; break; }
            if (a[mid] < target) lo = mid + 1;
            else hi = mid - 1;
        }
        System.out.println(found + ":" + checks);
    }
}