Search in an array with Binary search using JavaScript

In the realm of JavaScript programming, the ability to efficiently search through an array using the Binary search algorithm holds tremendous importance. This algorithmic technique, often regarded as an elegant and powerful solution, offers developers a high-performance approach to locate desired elements within a sorted array. Mastery of Binary search using JavaScript not only demonstrates one's proficiency in algorithmic problem-solving but also empowers developers to optimize search operations in their applications. In this article, we delve into the intricacies of implementing Binary search in JavaScript, exploring its step-by-step process and uncovering the rarely used words within the realm of this powerful algorithmic technique.

Problem Statement

The problem at hand involves searching for a target element within a sorted array, and the conventional linear search approach proves to be inefficient for larger arrays due to its time complexity.

Sample Input −

Array: [2, 5, 8, 12, 16, 23, 38, 42, 57, 69]
Target Element: 23


Sample Output −

The target element 23 was found at index 5.


Approach

In this article, we are going to see a number of different ways to solve the above problem statement in JavaScript −

• Iterative Binary Search

• Recursive Binary Search

• Array Methods

Method 1: Iterative Binary Search

In iterative binary search, initialize low and high as the lowest and highest indices. Enter a while loop until low is less than or equal to high. Calculate mid as the average of low and high. Check if the value at mid matches the target. If it does, return mid indicating a successful match. If the value at mid is less than the target, update low to mid + 1 to search in the right half. If the value at mid is greater than the target, update high to mid - 1 to search in the left half. If the while loop completes without finding the target, return -1 to indicate it wasn't found.

Example

The binarySearch function takes an array and a target value. It initializes low and high as the lowest and highest indices of the search space. Using a while loop, it calculates the mid index and checks if the value matches the target. If it does, the mid index is returned. If the value is less than the target, low is updated; if it's greater, high is updated. If the loop finishes without finding the target, -1 is returned.

function binarySearch(array, target) {
let low = 0;
let high = array.length - 1;

while (low <= high) {
let mid = Math.floor((low + high) / 2);
if (array[mid] === target) {
return mid; // Target found at index mid
} else if (array[mid] < target) {
low = mid + 1; // Discard the left half
} else {
high = mid - 1; // Discard the right half
}
}
}
const array = [2, 5, 8, 12, 16, 23, 38, 42, 57, 69];
const target = 23;


Output

The following is the console output −

Target found at index: 5


Method 3: Array Methods

The binarySearch function accepts an array and a target value as parameters. It employs the indexOf() method to quest for the target value and assigns the outcome to the index variable. By inspecting whether the indexOf() method yields a value distinct from -1, it ascertains the presence of a match. In the event that a match is detected, the function outputs the index. Nevertheless, if the indexOf() method returns -1, signifying the absence of the target, the function returns -1 to convey this state.

Example

The binarySearch function accepts an array and a target value as arguments and employs the indexOf() method to ascertain the index of the target within the array. It assigns the outcome to the index variable and yields the index if the target is discovered. Alternatively, it yields -1 if the target is not found.

function binarySearch(array, target) {
const index = array.indexOf(target);
return index !== -1 ? index : -1;
}
const array = [2, 5, 8, 12, 16, 23, 38, 42, 57, 69];
const target = 23;
console.log(Target found at index: \${binarySearch(array, target)});


Output

The following is the console output −

Target found at index: 5


Conclusion

In conclusion, employing the binary search algorithm to search within an array using JavaScript can be a highly efficacious approach. By leveraging the algorithm's logarithmic time complexity, we can expedite the search process and optimize performance, particularly when dealing with larger arrays. The judicious implementation of binary search empowers developers to efficiently locate desired elements, leading to improved user experiences and enhanced application functionality. Thus, integrating this method into JavaScript code can prove invaluable for handling vast datasets and achieving streamlined search operations.

Updated on: 04-Aug-2023

290 Views