Sponsored
Sponsored
This approach utilizes binary search to efficiently find the target element in a sorted array. Since the array is sorted, binary search can be applied, reducing the time complexity significantly compared to a linear search.
The core idea is to repeatedly divide the search interval in half. If the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half until the target is found or the interval is empty.
Time Complexity: O(log n), where n is the number of elements in the array.
Space Complexity: O(1), as no extra space is utilized.
1public class BinarySearch {
2 public static int binarySearch(int[] arr, int target) {
3 int left = 0, right = arr.length - 1;
4 while (left <= right) {
5 int mid = left + (right - left) / 2;
6 if (arr[mid] == target) return mid;
7 else if (arr[mid] < target) left = mid + 1;
8 else right = mid - 1;
9 }
10 return -1;
11 }
12
13 public static void main(String[] args) {
14 int[] arr = {1, 2, 3, 4, 5};
15 int target = 3;
16 int result = binarySearch(arr, target);
17 System.out.println("Element found at index: " + result);
18 }
19}
20
This Java program performs binary search on an integer array. The function iteratively computes the middle index, checks with the target, and shifts left
or right
boundaries accordingly. It outputs the index if the target is found.
The two-pointer approach helps to solve the problem with pointers or two index variables. This technique is beneficial when you need to minimize the number of iterations or traverse the array with controlled steps. Often used in problems involving arrays, especially when the sum or difference needs to be calculated between distinct elements.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(1), as no extra space is consumed.
This Java program explores the two-pointer method to find whether a pair sums to the target. It employs conditions between pointer positions to match or direct their movement efficiently across the array.