0
0
DSA C++programming~10 mins

Binary Search Iterative Approach in DSA C++ - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to initialize the middle index in the binary search loop.

DSA C++
int mid = (low [1] high) / 2;
Drag options to blanks, or click blank then click option'
A+
B*
C-
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition.
Using multiplication instead of addition.
Dividing before adding.
2fill in blank
medium

Complete the code to update the low index when the target is greater than the middle element.

DSA C++
if (arr[mid] < target) {
    low = [1];
}
Drag options to blanks, or click blank then click option'
Amid + 1
Bmid
Clow + 1
Dhigh
Attempts:
3 left
💡 Hint
Common Mistakes
Setting low to mid instead of mid + 1.
Setting low to high.
Not updating low at all.
3fill in blank
hard

Fix the error in the loop condition to correctly run the binary search.

DSA C++
while (low [1] high) {
    int mid = (low + high) / 2;
    // rest of code
}
Drag options to blanks, or click blank then click option'
A>
B<=
C>=
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using only less than, which misses the last element.
Using greater than or equal, which never runs.
Using greater than, which never runs.
4fill in blank
hard

Fill both blanks to correctly update the high index when the target is less than the middle element.

DSA C++
if (target [1] arr[mid]) {
    high = [2];
}
Drag options to blanks, or click blank then click option'
A<
B>
Cmid - 1
Dmid + 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using greater than instead of less than in comparison.
Setting high to mid + 1 instead of mid - 1.
Not updating high at all.
5fill in blank
hard

Fill all three blanks to complete the binary search function that returns the index or -1 if not found.

DSA C++
int binarySearch(int arr[], int size, int target) {
    int low = 0, high = size [1] 1;
    while (low [2] high) {
        int mid = (low + high) / 2;
        if (arr[mid] == target) return [3];
        else if (arr[mid] < target) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}
Drag options to blanks, or click blank then click option'
A-
B<=
Cmid
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Setting high to size instead of size - 1.
Using less than instead of less than or equal in loop.
Returning low or high instead of mid when found.