{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n" ] } ], "source": [ "# Write a Python program for binary search. \n", "# Binary Search : In computer science, a binary search or half-interval search algorithm finds the position of a target value\n", "# within a sorted array. The binary search algorithm can be classified as a dichotomies divide-and-conquer search algorithm and \n", "# executes in logarithmic time.\n", "\n", "def binary_search(item_listac,item):\n", "\tfirst = 0\n", "\tlast = len(item_list)-1\n", "\tfound = False\n", "\twhile( first<=last and not found):\n", "\t\tmid = (first + last)//2\n", "\t\tif item_list[mid] == item :\n", "\t\t\tfound = True\n", "\t\telse:\n", "\t\t\tif item < item_list[mid]:\n", "\t\t\t\tlast = mid - 1\n", "\t\t\telse:\n", "\t\t\t\tfirst = mid + 1\t\n", "\treturn found\n", "\t\n", "print(binary_search([1,2,3,5,8], 6))\n", "print(binary_search([1,2,3,5,8], 5))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.1" } }, "nbformat": 4, "nbformat_minor": 2 }