🚀 Mastering Binary Search
Binary Search is an efficient algorithm to find an element in a sorted array. Instead of scanning every element (like linear search), it smartly divides the search space in half each time, making it super fast! 💡
🔍 How Binary Search Works:
📝 Java Code for Binary Search:
public class BinarySearchExample {
// Binary Search method
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid; // 🎯 Found it!
if (arr[mid] > target) {
right = mid - 1; // Search left half
} else {
left = mid + 1; // Search right half
}
}
return -1; // ❌ Not found
}
public static void main(String[] args) {
int[] sortedArray = {1, 3, 5, 7, 9, 11, 15, 18};
int target = 7;
int result = binarySearch(sortedArray, target);
System.out.println(result != -1 ? "🎉 Element found at index: " + result : "❌ Element not found");
}
}
⏳ Time Complexity:
✅ Best case: O(1) (If the element is at the middle) ✅ Worst case: O(log N) (Dividing the array in half each step) ✅ Space Complexity: O(1) (No extra space used)
🌟 Why Use Binary Search?
🎯 More Problems on Binary Search:
🎯 Final Thoughts:
Mastering Binary Search gives you an edge in competitive programming and technical interviews. So, practice it, optimize it, and keep coding! 🚀✨