diff --git a/README.md b/README.md index 8c975b04..b118e2c1 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ This repository contains examples of various algorithms written on different pro | [Insertion Sort](https://en.wikipedia.org/wiki/Insertion_sort) | [:octocat:](insertion_sort/C) | | | [:octocat:](insertion_sort/Python) | | [Counting Sort](https://en.wikipedia.org/wiki/Counting_sort) | | | | [:octocat:](counting_sort/Python) | | [Radix Sort](https://en.wikipedia.org/wiki/Radix_sort) | | | | [:octocat:](radix_sort/Python) | +| [Binary Search](https://en.wikipedia.org/wiki/Binary_search_algorithm) | | | | [:octocat:](binary_search/Python) | ## Implemented Data Structures diff --git a/binary_search/Python/binary_search.py b/binary_search/Python/binary_search.py new file mode 100644 index 00000000..c42117ef --- /dev/null +++ b/binary_search/Python/binary_search.py @@ -0,0 +1,30 @@ +def binary_search(arr, key): + """ + Function to search an element 'key' in 'arr' array. + + :param arr: A list of element to sort. + """ + left = 0 + right = len(arr)-1 + while left <= right: + mid = int(left + (right-left)/2) + if arr[mid] == key: + return mid + elif arr[mid] < key: + left = mid+1 + else: + right = mid-1 + + return -1 + + +def main(): + arr = [1, 2, 3, 4, 5, 6] + key = 5 + print("Index of " + str(key) + " in the array: ", str(binary_search(arr, key))) + key = 8 + print("Index of " + str(key) + " in the array: ", str(binary_search(arr, key))) + + +if __name__ == '__main__': + main()