Last active
November 30, 2018 19:41
-
-
Save unacceptable/fd0fce55e10bbf30862e91773f5a5b51 to your computer and use it in GitHub Desktop.
This is a simple binary sort algorithm written in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import logging | |
import sys | |
import json | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
def main(): | |
arr = [5, 2, 3, 5, 7, 8, 1, 3, 6] | |
key = 3 | |
logger.info('Length of privided array: {}'.format(len(arr))) | |
Result = binarySearch(arr, key) | |
if not Result: | |
logger.info('Key {} not found.'.format(key)) | |
else: | |
logger.info('Key {} found!'.format(key)) | |
def binarySearch(array, key): | |
logger.info('Sorting unsorted array: {}'.format(json.dumps(array,indent=4))) | |
array = sorted(array) | |
logger.info('Sorted array: {}'.format(json.dumps(array,indent=4))) | |
left = 0 | |
right = len(array) - 1 | |
res = None | |
while left <= right and not res: | |
mid = (left + right) // 2 | |
logger.info('Evaluating the {} position.'.format(mid + 1)) | |
if array[mid] == key: | |
res = mid | |
else: | |
if array[mid] > key: | |
right = mid - 1 | |
else: | |
left = mid + 1 | |
return res | |
if __name__ == '__main__': | |
stdout_handler = logging.StreamHandler(sys.stdout) | |
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") | |
stdout_handler.setFormatter(formatter) | |
logger.addHandler(stdout_handler) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment