Searching is a fundamental process in computer science that is commonly used to locate certain items or values within a data structure. Depending on the qualities of the data and the specific requirements of the search, different data formats and algorithms are used for searching.
Binary search is an efficient searching algorithm specifically designed for sorted arrays or lists. It takes advantage of the fact that the array is sorted to reduce the search space in each iteration.
Conditions to be met before using Binary Search:
The binary search algorithm follows these steps:
Note: Binary search effectively removes half of the remaining entries by dividing the search interval in half at each step, resulting in a substantially faster search than linear search.
Operation | Time Complexity | Space Complexity |
---|---|---|
Binary Search | O(log N), where N is no. of elements | O(1) |
Comparison | O(1) | O(1) |
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1; // Target element not found
}
public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 10, 12, 14};
int target = 10;
int result = binarySearch(arr, target);
if (result == -1) {
System.out.println("Element not found");
} else {
System.out.println("Element found at index " + result);
}
}
}
In the given code:
binarySearch
method takes an array arr
and a target value target
as parameters and returns the index of the target value in the array or -1 if it is not found.low
and high
, to keep track of the search range.while
loop continues as long as low
is less than or equal to high
, indicating that elements are remaining to be searched.mid
is calculated as the average of low
and high
.arr[mid]
, the method returns mid
.arr[mid]
, the search is narrowed down to the left half of the remaining range by updating high
to mid - 1
.arr[mid]
, the search is narrowed down to the right half of the remaining range by updating low
to mid + 1
.main
method, we create an example array, arr
, and a target value, target
, to search for.binarySearch
method and print the result based on whether the target value was found or not.Given an array Arr[] of size L and a number N, you need to write a program to find if there exists a pair of elements in the array whose difference is N.
Example:
Input: L = 6, N = 78 arr[] = {5, 20, 3, 2, 5, 80} Output: 1 Explanation: (2, 80) have difference of 78.
class Solution
{
public boolean findPair(int arr[], int size, int n)
{
Arrays.sort(arr); // Sort the array in ascending order
for (int i = 0; i < arr.length; i++) {
int target = arr[i] + n;
int index = binarySearch(arr, target, i + 1, arr.length - 1);
if (index != -1) {
return true; // Pair found
}
}
return false; // Pair not found
}
public static int binarySearch(int[] arr, int target, int low, int high) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid; // Target found
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1; // Target not found
}
}
Time Complexity:
Arrays.sort(arr)
to sort the array with time complexity of O(N log N), where N is the size of the array.Space Complexity: Considering the sorting step as the dominant factor, the overall space complexity of the code is O(N).
Given two arrays: a1[0..n-1] of size n and a2[0..m-1] of size m. Task is to check whether a2[] is a subset of a1[] or not. Both the arrays can be sorted or unsorted. There can be duplicate elements.
Example:
Input: a1[] = {11, 7, 1, 13, 21, 3, 7, 3} a2[] = {11, 3, 7, 1, 7} Output: Yes Explanation: a2[] is a subset of a1[]
class Compute {
public String isSubset( long a1[], long a2[], long n, long m) {
//small array
Arrays.sort(a1); // Sort the first array
for (int i = 0; i < m; i++) {
if (binarySearch(a1, a2[i]) == -1) {
return "No"; // Element not found in a1[]
}
}
return "Yes"; // All elements of a2[] found in a1[]
}
public int binarySearch(long[] arr, long target) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) {
return mid; // Target found
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1; // Target not found
}
}
Time Complexity: overall time complexity of the code is O(N log N + M log N), where N & M is the size of arr1[] & arr2[].
Space Complexity: O(N)
In this code:
isSubset
method takes two long arrays (a1[]
and a2[]
) and their respective sizes (n
and m
) as parameters.a1[]
, is sorted using Arrays.sort(a1)
to enable binary search.for
loop iterates over each element in a2[]
and checks if it is found in a1[]
using the binarySearch
method.binarySearch
method performs binary search in the sorted array, arr[]
, and returns the index of the target if found or -1 if not found.a2[]
is not found in a1[]
, the method returns "No"
, indicating that a2[]
is not a subset of a1[]
.a2[]
are found in a1[]
, the method returns "Yes"
, indicating that a2[]
is a subset of a1[]
.Note: also read about DSA: Types of Tree
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…