Iterative Binary Search Algorithm (while Loop)
Data Structures and Algorithms | A Structured Practical Lesson on Iterative Binary Search
1. Learning Objectives and Prerequisites
Learning Objective: Understand how the Binary Search algorithm works using the iterative approach (while), trace changes in the search range indices (lowIndex, mid, and highIndex) step by step, and understand its operating requirements, time complexity, and space complexity.
Prerequisites: Lists and indexing, functions (def), the while loop, conditional statements (if / elif / else), and floor division (//).
2. Understanding the Concept and Algorithm Requirements
Binary Search is a highly efficient search algorithm used to locate a specific element within a list. It relies on a simple yet powerful idea: instead of examining each element individually from the beginning (Linear Search), we jump directly to the middle of the list, compare the middle element with the target value, and eliminate approximately half of the search range at each step.
Algorithm Requirements
- Sorted List: The list must be sorted in ascending order (from smallest to largest) or descending order (with reversed comparison logic). If the list is unsorted, the algorithm will not produce reliable results.
-
Search Range Boundaries: Define the starting index (
lowIndex = 0) and the ending index (highIndex = len(grades) - 1).
What Do We Use in the Code?
-
Function (
def): Encapsulates the algorithm, allowing it to be reused with any appropriately sorted list. -
Iteration Loop (
while): Continues searching as long as elements remain within the search range (lowIndex <= highIndex). -
Floor Division (
//): Calculates the middle index as an integer without a fractional part. -
Conditional Statements (
if / elif / else): Compare values and reduce the search range by approximately half during each iteration.
3. Complete Algorithm Code (Python 3)
def binarySearch(array, search, lowIndex, highIndex):
while lowIndex <= highIndex:
mid = lowIndex + (highIndex - lowIndex) // 2
if array[mid] == search:
return mid
elif array[mid] < search:
lowIndex = mid + 1
else:
highIndex = mid - 1
return -1
grades = [10, 12, 14, 15, 17, 19, 20]
search = 12
result = binarySearch(grades, search, 0, len(grades) - 1)
if result == -1:
print("Not found")
else:
print("found")
Expected Output
found
4. Line-by-Line Code Explanation and Execution Trace
The Loop Condition
while lowIndex <= highIndex:
The loop continues as long as the starting index is less than or equal to the ending index. When the starting index exceeds the ending index, the search range becomes empty, indicating that the target element was not found.
Calculating the Middle Index
mid = lowIndex + (highIndex - lowIndex) // 2
Calculates the middle index accurately. From a software engineering perspective, this formula is preferred over (lowIndex + highIndex) // 2 because it helps prevent integer overflow in programming languages that use fixed-width integers, such as C++ and Java. Python integers do not have this fixed-width overflow limitation.
Checking for a Match
if array[mid] == search:
return mid
If the middle element matches the target value, the function immediately returns its index and terminates.
Searching the Right Half
elif array[mid] < search:
lowIndex = mid + 1
If the middle element is smaller than the target value, the target, if present, must be located in the right half. Therefore, we move the starting index to the position immediately after the middle index.
Searching the Left Half
else:
highIndex = mid - 1
Otherwise, the target value is smaller than the middle element and, if present, must be located in the left half. Therefore, we move the ending index to the position immediately before the middle index.
Returning an Unsuccessful Search Result
return -1
If the loop terminates without finding the target element, the function returns -1 as a conventional indicator that the element was not found.
Execution Trace Table
List: [10, 12, 14, 15, 17, 19, 20]
Target Value: 12
| Iteration | lowIndex | highIndex | mid | array[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 15 | 15 > 12: Set highIndex = 2
|
| 2 | 0 | 2 | 1 | 12 | 12 == 12: Return index 1
|
Output: found
Visual Explanation of the Algorithm
Step 1 — Start with the Full Range
Index: 0 1 2 3 4 5 6
Value: 10 12 14 15 17 19 20
↑ ↑ ↑
low mid high
The middle value is 15. Since 15 > 12, we discard the midpoint and the right half of the list and continue searching the left half.
Step 2 — Reduce the Search Range
Index: 0 1 2
Value: 10 12 14
↑ ↑ ↑
low mid high
The new middle value is 12, which matches the target value.
Final Result
Target: 12
Index: 1
Iterations: 2
Status: found
5. Efficiency Analysis (Big-O) and Common Mistakes
Time Complexity — O(log n)
The search range is reduced by approximately half during each iteration. A sorted list containing one million elements requires at most 20 search iterations.
Space Complexity — O(1)
The iterative implementation uses only a fixed number of additional variables, regardless of the size of the input list, without requiring a recursive call stack.
Common Mistake 1 — Using an Unsorted List
Passing an unsorted list such as [20, 10, 15, 12] may cause the algorithm to return -1 even though the target element exists.
Common Mistake 2 — Forgetting the Equality Operator
Writing lowIndex < highIndex instead of lowIndex <= highIndex causes the algorithm to skip checking the last remaining element when both indices become equal.
Common Mistake 3 — Creating an Infinite Loop
Writing lowIndex = mid instead of lowIndex = mid + 1 may cause the program to enter an infinite loop when searching for an element that does not exist.
Common Mistake 4 — Forgetting to Subtract 1 from the List Length
Passing len(grades) instead of len(grades) - 1 may result in an IndexError because Python list indexing starts at zero.
6. Practical Exercise and Knowledge Assessment
Practical Exercise — Try It Yourself First
Modify the binarySearch function so that it also prints the index at which the target element was found and the number of search iterations performed by the algorithm.
Then test your modified function using the following values:
| Target Value | Description |
|---|---|
| 13 | An element that does not exist in the list. |
| 20 | The last element in the list. |
Knowledge Assessment Questions
- How many search iterations will the algorithm perform on the
gradeslist when searching for the value19? Trace the values oflowIndex,highIndex, andmid. - Why did we use floor division (
//) instead of regular division (/) when calculatingmid? - How should the condition
elif array[mid] < search:be modified if the list is sorted in descending order, from largest to smallest?

Top comments (1)
### Coming soon...
-∞ ← ⋯ ← -3 ← -2 ← -1 ← (0) → 1 → 2 → 3 → ⋯ → ∞🥸