{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 03:ALGORITHMS" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 03: Page 195" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found number 19 at the position 12\n" ] } ], "source": [ "def binarysearch(a,num): #function definition with its parameters 'a' is the inputlist\n", " #and 'num' number to be found\n", "\n", " first=0 #initially the first position is zero\n", " last=len(a)-1 #initially the last position is the total length of the inputlist-1\n", " found=False #boolean value to indicate if the number to be searched is found or not.\n", "\n", " while first<=last and not found:\n", " midpoint=(first+last)//2 #dividing the inputlist into two halves and comparing the number to be found with the midpoint.\n", "\n", " if a[midpoint]==num: #If the number to be found is equal to the midpoint returns the position.\n", " found=True\n", " else:\n", " if num 0) and (inputlist[pos-1] > val_current)):\n", " inputlist[pos] = inputlist[pos-1]\n", " pos = pos-1\n", " \n", " if pos != i:\n", " inputlist[pos] = val_current \n", " print(inputlist)\n", " return inputlist\n", "inputlist = [3,2,4,1,5]\n", "print sort_insertion(inputlist)\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.9" } }, "nbformat": 4, "nbformat_minor": 0 }