Skip to content

Commit

Permalink
add recursive binary search implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
gitgik committed Aug 25, 2020
1 parent 6344f2b commit 701828b
Showing 1 changed file with 105 additions and 0 deletions.
105 changes: 105 additions & 0 deletions recursion/recursive_binary_search.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Binary search recursive approach"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"def binary_search(A, value):\n",
" if len(A) == 0:\n",
" return -1\n",
" return binary_search_helper(A, 0, len(A) - 1, value)\n",
"\n",
"def binary_search_helper(A, left, right, value):\n",
" # base case\n",
" if left > right:\n",
" return -1\n",
" mid = (right + left) // 2\n",
" if A[mid] == value:\n",
" return mid\n",
" elif A[mid] > value:\n",
" return binary_search_helper(A, left, mid, value)\n",
" elif A[mid] < value:\n",
" return binary_search_helper(A, mid + 1, right, value)"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"-1"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"A = [1, 2, 3]\n",
"binary_search(A, 13)"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"array = [1, 2, 3, 5, 7, 13, 14, 16]\n",
"binary_search(array, 7)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"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.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

0 comments on commit 701828b

Please sign in to comment.