File size: 1,609 Bytes
ce5cd7e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
{
"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
}
|