{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Implementation of Binary Search\n", "\n", "In this notebook we will just implement two versions of a simple binary search. View the video lecture for a full breakdown!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Binary Search" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def binary_search(arr,ele):\n", " \n", " # First and last index values\n", " first = 0\n", " last = len(arr) - 1\n", " \n", " found = False\n", " \n", " \n", " while first <= last and not found:\n", " \n", " mid = (first+last)/2 # or // for Python 3\n", " \n", " # Match found\n", " if arr[mid] == ele:\n", " found = True\n", " \n", " # Set new midpoints up or down depending on comparison\n", " else:\n", " # Set down\n", " if ele < arr[mid]:\n", " last = mid -1\n", " # Set up \n", " else:\n", " first = mid + 1\n", " \n", " return found" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# list must already be sorted!\n", "arr = [1,2,3,4,5,6,7,8,9,10]" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "binary_search(arr,4)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "binary_search(arr,2.2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Recursive Version of Binary Search" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def rec_bin_search(arr,ele):\n", " \n", " # Base Case!\n", " if len(arr) == 0:\n", " return False\n", " \n", " # Recursive Case\n", " else:\n", " \n", " mid = len(arr)/2\n", " \n", " # If match found\n", " if arr[mid]==ele:\n", " return True\n", " \n", " else:\n", " \n", " # Call again on second half\n", " if ele