Add lesson 5: Binary search
3 changed files with 41 additions and 0 deletions
lessons/05-binary-search/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 5: Binary search | |
| 2 | + | |
| 3 | +We look at binary search the way working developers use it, with examples you can change and run right away. | |
| 4 | + | |
| 5 | +Full lesson: [https://glibcode.net/courses/algorithms/lessons/5](https://glibcode.net/courses/algorithms/lessons/5) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `binary_search.py`: binary search, iterative | |
| 10 | + | |
| 11 | +## Run it | |
| 12 | + | |
| 13 | +```sh | |
| 14 | +python3 binary_search.py | |
| 15 | +``` | |
| 16 | + | |
| 17 | +## Exercises | |
| 18 | + | |
| 19 | +See [exercises.md](exercises.md). Ask in the forum once you've tried. | |
lessons/05-binary-search/binary_search.py ADDED
| @@ -0,0 +1,17 @@ | ||
| 1 | +def binary_search(items, target): | |
| 2 | + lo, hi = 0, len(items) - 1 | |
| 3 | + while lo <= hi: | |
| 4 | + mid = (lo + hi) // 2 | |
| 5 | + if items[mid] == target: | |
| 6 | + return mid | |
| 7 | + if items[mid] < target: | |
| 8 | + lo = mid + 1 | |
| 9 | + else: | |
| 10 | + hi = mid - 1 | |
| 11 | + return -1 | |
| 12 | + | |
| 13 | + | |
| 14 | +if __name__ == "__main__": | |
| 15 | + data = [3, 8, 15, 23, 42, 57, 91] | |
| 16 | + print(binary_search(data, 42)) # 4 | |
| 17 | + print(binary_search(data, 5)) # -1 | |
lessons/05-binary-search/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 5 | |
| 2 | + | |
| 3 | +1. Add a comment above each block explaining what it does, in your own words. | |
| 4 | +2. Rewrite the main part so it runs twice with two different inputs, without copying the code. | |
| 5 | +3. Combine this lesson with the previous one: use something from both in a small program of your own. | |