Binary search is a fundamental algorithm every developer should understand, offering a highly efficient way to search for elements in a sorted array. This algorithm relies on a "divide and conquer" approach, allowing it to halve the search space with each step. In this article, we’ll explore binary search in both JavaScript and Java, covering iterative and recursive implementations.
Binary search is an algorithm designed to find the position of a target value within a sorted array. By leveraging the sorted nature of the array, binary search efficiently narrows down the search space, achieving a time complexity of O(log n). This is much faster than a linear search in large datasets.
Here’s a high-level overview:
Let’s dive into the code examples.
In JavaScript, the iterative approach uses a loop to perform binary search. Here’s what it looks like:
const binarySearch = (arr, target) => { let startIndex = 0; let endIndex = arr.length - 1; while (startIndex <= endIndex) { let midIndex = Math.floor((startIndex + endIndex) / 2); if (arr[midIndex] === target) { return midIndex; // Target found } else if (arr[midIndex] < target) { startIndex = midIndex + 1; // Search in the right half } else { endIndex = midIndex - 1; // Search in the left half } } return -1; // Target not found }; let nums = [-1, 0, 3, 5, 9, 12]; console.log(binarySearch(nums, 9)); // Output: 4 console.log(binarySearch(nums, 2)); // Output: -1
In Java, the iterative implementation is quite similar, with adjustments for Java syntax:
public class BinarySearchExample { public static int binarySearch(int[] arr, int target) { int startIndex = 0; int endIndex = arr.length - 1; while (startIndex <= endIndex) { int midIndex = (startIndex + endIndex) / 2; if (arr[midIndex] == target) { return midIndex; // Target found } else if (arr[midIndex] < target) { startIndex = midIndex + 1; // Search in the right half } else { endIndex = midIndex - 1; // Search in the left half } } return -1; // Target not found } public static void main(String[] args) { int[] nums = {-1, 0, 3, 5, 9, 12}; int target = 9; int result = binarySearch(nums, target); if (result != -1) { System.out.println("Element found at index: " + result); } else { System.out.println("Element not found in the array."); } } }
In both implementations:
For the recursive approach, we define the function so that it calls itself with updated indices until the target is found or the search range is empty.
In JavaScript, here’s a recursive binary search implementation:
const binarySearch = (arr, target) => { let startIndex = 0; let endIndex = arr.length - 1; while (startIndex <= endIndex) { let midIndex = Math.floor((startIndex + endIndex) / 2); if (arr[midIndex] === target) { return midIndex; // Target found } else if (arr[midIndex] < target) { startIndex = midIndex + 1; // Search in the right half } else { endIndex = midIndex - 1; // Search in the left half } } return -1; // Target not found }; let nums = [-1, 0, 3, 5, 9, 12]; console.log(binarySearch(nums, 9)); // Output: 4 console.log(binarySearch(nums, 2)); // Output: -1
In Java, a similar recursive binary search can be implemented as follows:
public class BinarySearchExample { public static int binarySearch(int[] arr, int target) { int startIndex = 0; int endIndex = arr.length - 1; while (startIndex <= endIndex) { int midIndex = (startIndex + endIndex) / 2; if (arr[midIndex] == target) { return midIndex; // Target found } else if (arr[midIndex] < target) { startIndex = midIndex + 1; // Search in the right half } else { endIndex = midIndex - 1; // Search in the left half } } return -1; // Target not found } public static void main(String[] args) { int[] nums = {-1, 0, 3, 5, 9, 12}; int target = 9; int result = binarySearch(nums, target); if (result != -1) { System.out.println("Element found at index: " + result); } else { System.out.println("Element not found in the array."); } } }
In each recursive call:
Binary search is ideal when:
If the array is unsorted, consider sorting it first (at an O(n log n) cost) or using a linear search if the dataset is small.
Binary search is a versatile and efficient algorithm for locating elements in sorted arrays. Whether you choose the iterative or recursive approach, understanding binary search is valuable for improving the performance of your applications. Try out both implementations in JavaScript and Java to get a feel for how they work, and see which fits best for your specific use case.
The above is the detailed content of Mastering Binary Search in JavaScript and Java: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!