Last active
January 18, 2020 21:33
-
-
Save MalikAbuShabab/0c2cc15cbc893f3f57a66dc30bac7ff8 to your computer and use it in GitHub Desktop.
Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.
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
""" | |
Suppose you give the following list of 8 items which is | |
in ascending order and we want to search for the value 25 | |
""" | |
matrix = [0,11,16,18,25,29,32,35] # Create matrix | |
def binary_search(m, matrix): | |
first =1 # Determine the starting first value | |
fond = 0 # Use it in checking find | |
last = len(matrix) # Determine the starting last value | |
middle = (first+last)/2 # We define the middle by relationship: (middle = (first+last)/2) | |
while first < last: # Check if (first < last) if not the loop will stop Because it could not be (first > last) | |
if matrix[int(middle)-1] == m: # Check if middle value equal The value we are looking for (m) | |
print("index is :", int(middle)-1) # print the index of the value | |
fond = 1 # the fond value equal 1 | |
break # to stop the loop | |
elif matrix[int(middle)-1] < m: # The number we are looking for is 25 greater than the intermediate element 18, so we move the starting index first to the element that follows the intermediate | |
first = middle+1 # we move the starting index first to the element that follows the intermediate | |
middle = (first + last) / 2 # update middle | |
elif matrix[int(middle)-1] > m: # if middle value is bigger than value we are looking for ,We change the value of last to the element immediately before the mean | |
last = middle - 1 # We change the value of last to the element immediately before the mean | |
middle = (first + last) / 2 # update middle | |
if fond == 0: # Check if we find the value we’re looking for in the array or not | |
print("Not Fond !") | |
# Test Code | |
binary_search(25,matrix) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment