📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    Complete the while loop condition for an iterative

    binary search implementation. def binary_search(arr, target):     low = 0     high = len(arr) - 1     while __________: # Line to complete         mid = low + (high - low) // 2         if arr[mid] == target:             return mid         elif arr[mid] < target:             low = mid + 1         else:             high = mid - 1     return -1
    A low < high Correct Answer Incorrect Answer
    B low <= high Correct Answer Incorrect Answer
    C low != high Correct Answer Incorrect Answer
    D low + 1 < high Correct Answer Incorrect Answer
    E mid != target Correct Answer Incorrect Answer

    Solution

    • Code Analysis: o low and high define the current search space. o The loop needs to continue as long as there's a potential range to search, including the case where low and high point to the same element. • Explanation of Correct Answer (B): low <= high o This condition ensures that the loop continues as long as the low index is less than or equal to the high index. This covers cases where low and high are equal (meaning there's one element left to check) and cases where low is less than high (meaning there's a range of elements). If low becomes greater than high, it means the search space has become empty, and the target is not found.

    Practice Next
    ask-question