17
DSA - Binary Search Algorithm
Hello Guys today i am going to show you Binary Search algorithm implementation in Javascript and Python.
Lets get started...
BINARY SEARCH -
Binary Search is searching technique which works on Divide and Conquer approach. It used to search any element in a sorted array.
As compared to linear, binary search is much faster with Time Complexity of O(logN) whereas linear search algorithm works in O(N) time complexity.
Input : arr[] = {1, 3, 5, 7, 8, 9}
x = 5
Output : Element found!
Input : arr[] = {1, 3, 5, 7, 8, 9}
x = 6
Output : Element not found!
JAVASCRIPT IMPLEMENTATION -
function BinarySearch(arr, x) {
let start=0, end=arr.length-1;
// Iterate while start not meets end
while (start<=end){
// Find the mid index
let mid=Math.floor((start + end)/2);
// If element is present at mid, return True
if (arr[mid]===x){
console.log(arr[mid]);
return true;
}
// Else look in left or right half accordingly
else if (arr[mid] < x)
start = mid + 1;
else
end = mid - 1;
}
return false;
}
const arr = [1,0,90,899,6,4,67,343,901];
const result = BinarySearch(arr,10) ? 'Element found' : 'Element not found';
console.log(result);
OUTPUT -
343
Element found
PYTHON IMPLEMENTATION -
import math
def binarysearch(Arr,element):
start = 0
end = len(Arr) - 1
while start <= end:
mid = start + (end - start) // 2;
if Arr[mid] == element:
print(Arr[element])
return True
elif Arr[mid] < element:
start = mid + 1
else:
end = mid - 1
return -1
items = [1,2,3,4,5,6,7,8,9,10]
result ='Element found' if binarysearch(items,5) else 'Element not found'
print(result)
OUTPUT -
6
Element found
NOTE - This blog is just for academic purpose and for students who wants to learn Binary search implementation for their Academics.
THANK YOU FOR READING THIS POST AND IF YOU WANT TO GIVE ANY SUGGESTION OR FIND ANY MISTAKE PLEASE MENTION IT IN THE COMMENT SECTION
Source - https://www.geeksforgeeks.org/
17