Practice
Binary Search on a Sorted Array
2024/Oct/Nov·Variant 1
MEDIUMAlgorithms
Array Data holds 8 integers already sorted into ascending order. Write function BinarySearch(Target) that returns the 1-based index of Target, or -1 if it is not present, using the binary search algorithm (not a linear scan).
Input: 8 sorted integers, then the target value.
Output: The 1-based index, or -1.
Example:
Input: 2
5
8
12
16
23
38
45
23
Output: 6
Premium is coming soon. All grading features are currently unlocked.
Sample Test Cases
Test 1: Middle-ish value found
Inputs: 2, 5, 8, 12, 16, 23, 38, 45, 23
Expected: 6
Test 2: First element
Inputs: 2, 5, 8, 12, 16, 23, 38, 45, 2
Expected: 1
Test 3: Not present, larger than every element
Inputs: 2, 5, 8, 12, 16, 23, 38, 45, 100
Expected: -1