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
      }
   }
   return -1; // Target not found
}
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

Method 2: Recursive Binary Search

In recursive binary search, a binarySearch function is defined with parameters for an array, target value, low and high indices. It checks if low is greater than high, returning -1 if true. The mid index is calculated as the average of low and high. If the value at the mid index matches the target, the mid index is returned. If the value at the mid index is less than the target, binarySearch is recursively called with the right half of the search space. If the value at the mid index is greater than the target, binarySearch is recursively called with the left half of the search space. This process continues until the target is found or the search space is exhausted, returning -1 if the target was not found.

Example

The binarySearch function is a recursive implementation that searches for a target value within an array. It checks if the search space is empty by comparing the low and high indices. If so, it returns -1. Otherwise, it calculates the mid index, checks if the value at mid matches the target, and returns mid if it does. If the value at mid is less than the target, it recursively calls itself with the right half of the search space. If the value at mid is greater, it recursively calls itself with the left half. This process continues until the target is found or it's determined to be absent.

function binarySearch(array, target, low = 0, high = array.length - 1) {
   if (low > high) {
      return -1; // Target not found
   }
   let mid = Math.floor((low + high) / 2);
   if (array[mid] === target) {
      return mid; // Target found at index mid
   } else if (array[mid] < target) {
      return binarySearch(array, target, mid + 1, high); // Search the right half
   } else {
      return binarySearch(array, target, low, mid - 1); // Search the left half
   }
}
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

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

391 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements