From f985d33eb61cd1eb01dc72cd361e5548d2c1cf75 Mon Sep 17 00:00:00 2001 From: Aditya Bhargava Date: Wed, 2 Mar 2016 14:03:34 -0800 Subject: [PATCH] first commit: code for chapter 1 --- .../python/01_binary_search.py | 28 +++++++++++++++++++ README.md | 8 ++++++ 2 files changed, 36 insertions(+) create mode 100644 01_introduction_to_algorithms/python/01_binary_search.py create mode 100644 README.md diff --git a/01_introduction_to_algorithms/python/01_binary_search.py b/01_introduction_to_algorithms/python/01_binary_search.py new file mode 100644 index 0000000..d053232 --- /dev/null +++ b/01_introduction_to_algorithms/python/01_binary_search.py @@ -0,0 +1,28 @@ +def binary_search(list, item): + # low and high keep track of which part of the list you'll search in. + low = 0 + high = len(list) - 1 + + # While you haven't narrowed it down to one element ... + while low <= high: + # ... check the middle element + mid = (low + high) // 2 + guess = list[mid] + # Found the item. + if guess == item: + return mid + # The guess was too high. + if guess > item: + high = mid - 1 + # The guess was too low. + else: + low = mid + 1 + + # Item doesn't exist + return None + +my_list = [1, 3, 5, 7, 9] +print binary_search(my_list, 3) # => 1 + +# 'None' means nil in Python. We use to indicate that the item wasn't found. +print binary_search(my_list, -1) # => None diff --git a/README.md b/README.md new file mode 100644 index 0000000..e15dbf8 --- /dev/null +++ b/README.md @@ -0,0 +1,8 @@ +# Grokking Algorithms + +This is the code in my book [Grokking Algorithms](https://www.manning.com/bhargava). + +# Contributing + +- 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! +- I'm pretty responsive to PRs. That is the quickest way to contribute to this repo.