Why Binary Search and What Sorted Order Gives You in DSA C - Performance Analysis
We want to understand why searching in a sorted list is faster with binary search.
How does sorting help us find items quickly?
Analyze the time complexity of the following binary search code.
int binarySearch(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
This code searches for a target value in a sorted array by repeatedly dividing the search range in half.
Look at what repeats in the code.
- Primary operation: Checking the middle element of the current search range.
- How many times: The search range halves each time until the target is found or the range is empty.
Each step cuts the search space in half, so the number of steps grows slowly as the list grows.
| Input Size (n) | Approx. Operations (mid checks) |
|---|---|
| 10 | About 4 |
| 100 | About 7 |
| 1000 | About 10 |
Pattern observation: Doubling the input size adds only one more step.
Time Complexity: O(log n)
This means the number of steps grows very slowly even if the list gets much bigger.
[X] Wrong: "Binary search checks every element like linear search, so it is O(n)."
[OK] Correct: Binary search skips half the list each time, so it does far fewer checks than linear search.
Understanding binary search shows you how sorting helps speed up searching, a key skill in many coding problems.
"What if the array was not sorted? How would that affect the time complexity of searching with binary search?"
Practice
Solution
Step 1: Understand binary search working
Binary search works by repeatedly dividing the sorted list and comparing the middle element to the target value.Step 2: Importance of sorted order
Sorted order allows us to decide which half to discard after each comparison, making search efficient.Final Answer:
Because binary search divides the list and compares middle elements to find the target efficiently -> Option CQuick Check:
Sorted list needed for binary search = Because it divides and compares middle elements [OK]
- Thinking binary search works on unsorted lists
- Assuming binary search needs duplicates
- Believing binary search requires odd length lists
arr of size n?Solution
Step 1: Identify correct index range for array
Array indices in C start at 0 and end at n-1, so low = 0 and high = n-1.Step 2: Correct loop condition for binary search
Loop continues while low is less than or equal to high to cover all elements.Final Answer:
int low = 0, high = n - 1; while (low <= high) { ... } -> Option BQuick Check:
Array indices 0 to n-1 and loop while low <= high [OK]
- Starting low at 1 instead of 0
- Using high = n instead of n-1
- Using < instead of <= in loop condition
int arr[] = {2, 4, 6, 8, 10};
int low = 0, high = 4, mid;
int target = 6;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == target) {
printf("Found at index %d", mid);
break;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}Solution
Step 1: Initialize variables and first mid calculation
low=0, high=4, mid=(0+4)/2=2; arr[2]=6 matches target 6.Step 2: Check condition and print result
Since arr[mid] == target, print "Found at index 2" and break loop.Final Answer:
Found at index 2 -> Option DQuick Check:
Target 6 found at index 2 [OK]
- Calculating mid incorrectly
- Off-by-one errors in index
- Printing wrong index
int arr[] = {1, 3, 5, 7, 9};
int low = 0, high = 5, mid;
int target = 7;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == target) {
printf("Found at %d", mid);
break;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}Solution
Step 1: Check array index bounds
Array size is 5, so highest index is 4. Setting high=5 causes out-of-bounds access.Step 2: Fix high initialization
Set high = 4 to stay within valid indices and avoid runtime errors.Final Answer:
Change high to 4 instead of 5 -> Option AQuick Check:
Array indices 0 to 4, high must be 4 [OK]
- Setting high to array size instead of size-1
- Changing low incorrectly
- Incorrect mid calculation
arr = {1, 3, 5, 7, 9, 11, 13}, you want to find the smallest element greater than or equal to 8 using binary search. Which approach correctly finds this element?Solution
Step 1: Understand the problem
We want the smallest element >= 8, which may not be exactly 8 in the array.Step 2: Modify binary search for lower bound
When arr[mid] >= 8, move high to mid - 1 to find smaller candidates; else move low to mid + 1.Step 3: After loop, low points to smallest element >= 8
This approach finds the correct element (9 at index 4).Final Answer:
Modify binary search to move high = mid - 1 when arr[mid] >= 8, else low = mid + 1 -> Option AQuick Check:
Lower bound binary search finds smallest element ≥ target [OK]
- Using normal binary search without modification
- Sorting array again unnecessarily
- Choosing linear search over binary search
Ready to prove it?
Pass the test and this pattern moves unknown
