Binary Search in Python: Simple & Powerful Algorithm

🔍 Binary Search in Python — Simple & Powerful Have you ever searched for a name in a phone book? You don’t check every page… you jump to the middle, right? 👉 That’s exactly how Binary Search works! 💡 What is Binary Search? Binary Search is a fast way to find an element in a sorted list by repeatedly dividing the search space into half. ⚙️ How it works (Step-by-Step): 1️⃣ Find the middle element 2️⃣ Compare it with the target 3️⃣ If equal → ✅ Found 4️⃣ If smaller → Search right half 5️⃣ If larger → Search left half 6️⃣ Repeat until found or not present 🐍 Python Code: def binary_search(arr, target): left, right = 0, len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid elif arr[mid] < target: left = mid + 1 else: right = mid - 1 return -1 # Example arr = [10, 20, 30, 40, 50] print(binary_search(arr, 30)) 🚀 Why use Binary Search? ✔ Very fast → O(log n) time ✔ Works great for large data ✔ Common in real-world systems ⚠️ Important: Binary Search works only when the data is sorted. 📌 Real-Life Examples: • Searching contacts 📱 • Finding words in a dictionary 📖 • Database searching 💾 💬 “Work smarter, not harder — Binary Search proves it!” #Python #Algorithms #Coding #Programming #BinarySearch #LearnToCode #Tech

  • diagram

To view or add a comment, sign in

Explore content categories