Algorithms with Javascript

vishal rana
3 min readNov 5, 2022

--

In this series, we’ll see integration of some of the most commonly used algorithms used in programming world. Algorithms make life easier while thinking solution for a problem. Some people got scared once they heard the name algorithms. The only thing is ,you need to understand the concept and practice it yourself. Once you do that, you’ll love it.

This will be series of blogs in which we’ll cover below algorithms: 👉

Let’s start with Binary search:

Binary search is one of the easiest algorithms to start with. Binary search works on a sorted array. Binary search is used to find an element inside a sorted array(Assuming that the element exist). Binary search has a worst case time complexity of O(log(n)).

Binary search take a sorted array, divide the array in half, compare the value , if value(that we are looking for) is less than current index value then it means value (that we are looking for) is in left array else it is is right array.

sortedArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]// let's suppose, we want to search index of 5 in the array.Steps:
- we need to keep track of min and max index to compare the value between.
- In the starting , we have min = 0 and max= 14(size of array-1)
- we need to find the mid of both the index using : Math.floor((min + max)/2)
- we check if the current index value is greater than or less than searched value.
- if it is less then max become the mid else min become the max.
- we need to do this until we find an index.

Above steps will simple give you a little information for the working of the algo. Let’s jump into the code. 👇

const binarySearch = (sortedArray, element)=>{
let min = 0; // taking min as starting value of array
let max = sortedArray.length -1; // taking max as length of array
// we need to create a variable to track index of the value
let index = -1; //setting it to -1 so that we know, we have found the index of not.
// we need to start a while loop until index is -1 , means not found
while(index == -1){
// let's check for edge element
if(sortedArray[min] == element){
//min element match the condition
index = min;
} else if(sortedArray[max] == element){
// last element match the condition
index = max;
} else{
// dividing the array and comparing the values
let mid = Math.floor((min+max)/2);
if(sortedArray[mid] < element){
// element exist in right
min = mid;
} else if(sortedArray[mid] > element ){
// element exist in left
max = mid;
}else{
// we reach the index
index = mid;
}
}
}
return index;
}
console.log(binarySearch([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],5))

If you still have confusion understanding binary search , leave a comment and i’ll try to solve your confusion. In the next blog, we’ll go through the working on Quick sort.

--

--