Blog 4:DSA Bubble Sort in JAVA
Binary Search Algorithm :
1. Sort the array (if not already sorted).
2. Initialize two pointers: low = 0 and high = arr.length - 1.
3. Calculate the middle index: mid = low + (high - low) / 2.
4. Compare the target value with arr[mid]:
o If the target is equal to arr[mid], return mid.
o If the target is smaller than arr[mid], search the left subarray.
o If the target is larger than arr[mid], search the right subarray.
5. Repeat until the target is found or low > high.
Java Program: Binary Search
import java.util.*;
public class BinarySearch {
// Function to perform Binary Search
public static int binarySearch(int[] arr, int target) {
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid; // Return the index if found
} else if (arr[mid] < target) {
low = mid + 1; // Search in the right subarray
} else {
high = mid - 1; // Search in the left subarray
}
}
return -1; // Return -1 if not found
}
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int target = 30;
int result = binarySearch(arr, target);
if (result != -1) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found.");
}
}
}
Step-by-Step Execution
1. Input Array: [10, 20, 30, 40, 50] (Sorted), Target: 30.
2. First Iteration:
o low = 0, high = 4, mid = 2.
o Compare arr[mid] (30) with 30. Match found at index 2.
Output: Element found at index: 2.
Applications of Binary Search
1. Large Sorted Arrays: Efficient for datasets where nn is large.
2. Databases: Used for searching in sorted database tables.
3. Finding Bounds: Used in algorithms like finding the smallest/largest
element satisfying a condition.
4. Strings: Works on sorted strings for dictionary-like operations.