Skip to content

Commit f985d33

Browse files
committed
first commit: code for chapter 1
0 parents  commit f985d33

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
def binary_search(list, item):
2+
# low and high keep track of which part of the list you'll search in.
3+
low = 0
4+
high = len(list) - 1
5+
6+
# While you haven't narrowed it down to one element ...
7+
while low <= high:
8+
# ... check the middle element
9+
mid = (low + high) // 2
10+
guess = list[mid]
11+
# Found the item.
12+
if guess == item:
13+
return mid
14+
# The guess was too high.
15+
if guess > item:
16+
high = mid - 1
17+
# The guess was too low.
18+
else:
19+
low = mid + 1
20+
21+
# Item doesn't exist
22+
return None
23+
24+
my_list = [1, 3, 5, 7, 9]
25+
print binary_search(my_list, 3) # => 1
26+
27+
# 'None' means nil in Python. We use to indicate that the item wasn't found.
28+
print binary_search(my_list, -1) # => None

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Grokking Algorithms
2+
3+
This is the code in my book [Grokking Algorithms](https://www.manning.com/bhargava).
4+
5+
# Contributing
6+
7+
- The examples in this book are in Python, but I'd like to get examples in Ruby, Javascript, C, and other languages too. Please add examples in other languages!
8+
- I'm pretty responsive to PRs. That is the quickest way to contribute to this repo.

0 commit comments

Comments
 (0)