🚀 Mastering Binary Search

🚀 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:

  1. Start with a sorted array.
  2. Find the middle element.
  3. If it's the target, return its index 🎯.
  4. If the target is smaller, search in the left half.
  5. If the target is larger, search in the right half.
  6. Repeat until the element is found or no elements are left.


📝 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?

  • Super fast 🚀 compared to linear search for large data.
  • Used in databases, autocomplete suggestions, dictionary lookups, etc.
  • A must-know for coding interviews & problem-solving! 💡


🎯 More Problems on Binary Search:

  1. Find the First and Last Position of an Element in a Sorted Array
  2. Find the Square Root of a Number using Binary Search
  3. Search in a Rotated Sorted Array
  4. Find the Peak Element in an Array
  5. Find the Insertion Position of a Target Value
  6. Count the Occurrences of an Element in a Sorted Array
  7. Find the Minimum in a Rotated Sorted Array
  8. Binary Search on an Infinite Sorted Array
  9. Find the Closest Element to a Given Value
  10. Binary Search on a Nearly Sorted Array


🎯 Final Thoughts:

Mastering Binary Search gives you an edge in competitive programming and technical interviews. So, practice it, optimize it, and keep coding! 🚀✨


To view or add a comment, sign in

More articles by Aditya Gupta

Explore content categories