Why Binary Search and What Sorted Order Gives You in DSA Go - 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 this binary search code.
func binarySearch(arr []int, target int) int {
left, right := 0, len(arr)-1
for left <= right {
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 number in a sorted list by repeatedly dividing the search area 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, repeating until the target is found or range is empty.
Each step cuts the search area in half, so the number of steps grows slowly as the list gets bigger.
| Input Size (n) | Approx. Operations (mid checks) |
|---|---|
| 10 | About 4 |
| 100 | About 7 |
| 1000 | About 10 |
Pattern observation: Doubling the list size adds only one extra step.
Time Complexity: O(log n)
This means the number of steps grows slowly, making search very fast even for large lists.
[X] Wrong: "Binary search is always faster than linear search no matter what."
[OK] Correct: Binary search only works on sorted lists; if the list is unsorted, linear search is needed first or sorting must be done, which takes extra time.
Understanding binary search shows you how sorting helps speed up searching, a key skill for efficient coding and problem solving.
"What if the list was not sorted? How would the time complexity of searching change?"
Practice
Solution
Step 1: Understand binary search logic
Binary search splits the list into halves and decides which half to search next based on order.Step 2: Importance of sorted order
Without sorted order, we cannot decide which half to discard, so binary search fails.Final Answer:
Because it relies on dividing the list based on order to find elements quickly -> Option AQuick Check:
Sorted list needed for binary search = Because it relies on dividing the list based on order to find elements quickly [OK]
- Thinking binary search works on unsorted lists
- Believing binary search compares all elements
- Assuming binary search needs unique elements
arr to find target?Solution
Step 1: Check binary search loop and boundaries
left, right := 0, len(arr)-1 for left <= right { mid := (left + right) / 2 if arr[mid] == target { return mid } else if arr[mid] < target { left = mid + 1 } else { right = mid - 1 } } return -1 correctly initializes left and right, uses <=, and updates left and right properly.Step 2: Identify errors in other options
for i := 0; i < len(arr); i++ { if arr[i] == target { return i } } return -1 is linear search, not binary. left, right := 0, len(arr) for left < right { mid := (left + right) / 2 if arr[mid] == target { return mid } else if arr[mid] > target { left = mid + 1 } else { right = mid - 1 } } return -1 has wrong boundary and updates. left, right := 0, len(arr)-1 for left <= right { mid := (left + right) / 2 if arr[mid] == target { return mid } else if arr[mid] > target { right = mid - 1 } else { left = mid - 1 } } return -1 incorrectly updates left pointer.Final Answer:
Option A code correctly implements binary search -> Option AQuick Check:
Correct binary search syntax = left, right := 0, len(arr)-1 for left <= right { mid := (left + right) / 2 if arr[mid] == target { return mid } else if arr[mid] < target { left = mid + 1 } else { right = mid - 1 } } return -1 [OK]
- Using linear search instead of binary search
- Wrong loop conditions like < instead of <=
- Incorrectly updating left or right pointers
arr := []int{2, 4, 6, 8, 10}
target := 6
left, right := 0, len(arr)-1
for left <= right {
mid := (left + right) / 2
if arr[mid] == target {
fmt.Println(mid)
break
} else if arr[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}Solution
Step 1: Trace binary search steps
Initial left=0, right=4, mid=2 (value 6). arr[mid] == target, so print 2 and break.Step 2: Confirm output
The printed index is 2, which is the position of 6 in the slice.Final Answer:
2 -> Option DQuick Check:
Index of 6 in arr = 2 [OK]
- Confusing index with value
- Miscomputing mid index
- Ignoring break after finding target
arr := []int{1, 3, 5, 7, 9}
target := 7
left, right := 0, len(arr)-1
for left < right {
mid := (left + right) / 2
if arr[mid] == target {
fmt.Println(mid)
break
} else if arr[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}Solution
Step 1: Analyze loop condition
The loop uses left < right, which misses the case when left == right, possibly skipping the last element.Step 2: Correct loop condition
Changing to left <= right ensures all elements are checked, fixing the bug.Final Answer:
Loop condition should be left <= right instead of left < right -> Option BQuick Check:
Loop must cover all indices = Loop condition should be left <= right instead of left < right [OK]
- Using < instead of <= in loop condition
- Changing mid calculation unnecessarily
- Thinking array must be reversed
arr := []int{1, 3, 5, 7, 9, 11, 13}, you want to find the smallest element greater than or equal to target = 8. Which modification to binary search helps achieve this?Solution
Step 1: Understand the problem
We want the smallest element >= target, so we track candidates when arr[mid] >= target.Step 2: Modify binary search accordingly
If arr[mid] < target, move left to mid + 1; else move right to mid - 1 and save mid as potential answer.Final Answer:
When arr[mid] < target, move left to mid + 1; else move right to mid - 1 and track mid as potential answer -> Option CQuick Check:
Track candidate when arr[mid] >= target = When arr[mid] < target, move left to mid + 1; else move right to mid - 1 and track mid as potential answer [OK]
- Not tracking potential answer index
- Moving pointers incorrectly
- Using linear search instead of binary search
Ready to prove it?
Pass the test and this pattern moves unknown
