diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Binary Search - Python/Binary Search.py b/Binary Search - Python/Binary Search.py new file mode 100644 index 0000000..511aaa4 --- /dev/null +++ b/Binary Search - Python/Binary Search.py @@ -0,0 +1,22 @@ +def binary_search(values, i, j, key): + if not i < j: + return -1 + mid = (i + j) // 2 + if values[mid] < key: + return binary_search(values, mid + 1, j, key) + elif values[mid] > key: + return binary_search(values, i, mid, key) + else: + return mid + + +values = input('Enter the sorted numbers: \n') +values = values.split() +values = [int(x) for x in values] +key = int(input('The number to search for: ')) + +index = binary_search(values, 0, len(values), key) +if index < 0: + print('{} was not found.'.format(key)) +else: + print('{} was found at index {}.'.format(key, index))