{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "
Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.
\n",
"Example 1:
Input:\n", "\n", "nums= [-1,0,3,5,9,12],target= 9\n", "Output: 4\n", "Explanation: 9 exists innumsand its index is 4\n", "\n", "
Example 2:
\n", "\n", "Input:\n", "\n", "nums= [-1,0,3,5,9,12],target= 2\n", "Output: -1\n", "Explanation: 2 does not exist innumsso return -1\n", "
\n", "\n", "
Note:
\n", "\n", "nums are unique.n will be in the range [1, 10000].nums will be in the range [-9999, 9999].\n", "Source \n", "
Solve it both iteratively and recursively. Solve it using built-in methods too.
" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "def binary_search(nums, target):\n", " \"\"\"Recursive implementation of binary search\"\"\"\n", " def helper(left, right):\n", " if right < left: # base case: target not present\n", " return -1\n", "\n", " nonlocal nums, target\n", " mid = left + (right-left)//2\n", "\n", " if nums[mid] == target: # base case: target at middle index\n", " return mid\n", " if target > nums[mid]:\n", " return helper(mid+1, right)\n", " else:\n", " return helper(left, mid-1)\n", "\n", "\n", "\n", " return helper(0, len(nums)-1)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "def binary_search(nums, target):\n", " \"\"\"Using Built-in method index()\"\"\"\n", " try:\n", " return nums.index(target)\n", " except ValueError: # index() returns an error if target is not in nums\n", " return -1" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "from bisect import bisect_left\n", "\n", "def binary_search(nums, target):\n", " \"\"\"Using Built-in method bisect_left()\"\"\"\n", " i = bisect_left(nums, target) \n", " return i if i != len(nums) and nums[i] == target else -1 " ] } ], "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.8.2" } }, "nbformat": 4, "nbformat_minor": 1 }