Binary Search
What is a Binary Search?
- Binary Search helps you find elements in a sorted list of items with data by dividing the list into two parts and comparing the left, right, and middle items.
- If the middle item matches, return that item,
- If it is less than the middle, it goes to the left, setting the middle to the right and repeat the above procedure.
- If the item is more than the middle, it sets the left to middle + 1 and repeats the procedure mentioned in the above points until the item matches.
- If no items matched in the array items, it will return none or a null value.
Why do you need Binary Search?
- It is used in phone books, dictionaries and placed where the data is sorted in ascending order or descending order in alphabets wise or numerically.
- Our phone book in mobiles uses this binary search to match the names and display them.
Pseudo code of Binary Search:
items = ["a","b","c","d","e"]
left = 0, right = length of the items
item = "d" // to be found
while left < right then
middle = left + right /2
if items[middle] equals item
return middle
if items[middle] less than item
right = middle - 1
else then
left = middle + 1
The pseudo code above describes the algorithm of the Binary Search. The
code may have somw tweaking around the things.
Binary search algorithm to search for the target number in Python from a
list.
numbers_list = [1,3,5,7,8,9,10,20]
target = 10
left = 0
right = len(numbers_list)
while(left<right):
middle = (left+right) // 2
if(numbers_list[middle] == target):
return middle
elif (numbers_list[middle] < target):
right = middle - 1
else:
left = middle + 1
The above code returns the target value of 10 from the list. If you have an n-size array or list in a sorted array, you can use this algorithm to get the value and return its index.
Conclusion:
I hope you find this article useful and learn how to use Binary search and how to implement.
0 Comments
If you have any doubts or any topics that you want to know more about them please let me know