In the programming world, we frequently need to search for a particular element on the list or array. one of the methods we can use for searching that element with using algorithms binary search. on this blog, we will discuss the basic concept of binary search, how this algorithms work, and example of its implementations in javascript.
-
Check if the element at the index "mid" of the array is equal to the target value. If it is, return the index of the array as the result.
-
If the target value is greater than the element at the "mid" index, we can conclude that the target value is located in the right part of the array. Therefore, we can ignore the left part of the array. To do that, we set the "left" pointer to mid + 1.
-
If the target value is less than the element at the "mid" index, we can conclude that the target value is located in the left part of the array. Therefore, we can ignore the right part of the array. To do that, we set the "right" pointer to mid _ 1.
-
Repeat the steps described above until we either find an element equal to the target value or until the "left" pointer becomes greater than the "right" pointer. If the "left" pointer becomes greater than the "right" pointer, it means that the target does not exist inside the array, and in such case, we can return -1 to indicate that the target was not found.
Using the binary search approach described above, we can perform an efficient search in logarithmic time relative to the size of the array.
If you want to try the code you go to this
link