def binary_search(values, low, high, x): if high >= low: mid = (high + low) // 2 if values[mid] == x: return mid elif values[mid] > x: return binary_search(values, low, mid - 1, x) else: return binary_search(values, mid + 1, high, x) else: return -1 values = [ 2, 3, 4, 10, 40 ] x = 10 result = binary_search(values, 0, len(values)-1, x) if result != -1: print("Element is present at index", str(result)) else: print("Element is not present in array") ''' Binary Search Algorithm: 1. Initializing two variables and defining a base case. 2. If the base case is true, mid is calculated. 3. a) If searched element is equal to calculated mid value, return mid value. b) elseif searched element is greater then mid, replace higher value with the searched value. c) else replace lower value with the searched value.'''
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question