Python एल्गोरिदम

Binary Search in Python

Find any value in a sorted list of a million items in about 20 steps by halving the search range every time.

  • मध्यम
  • 2 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • low, middle and high indexes
  • Why the list must be sorted
  • The bisect module
Find 17 in [3, 8, 12, 17, 25, 31]
3low
8
12middle ✗
17✓ index 3
25
31high
17 > 12, so the left half is dropped; the next middle is 17.

Halve the range every step

Binary search हर comparison के बाद search range को आधा कर देता है।

मुख्य बातें

  1. Compare the target with the middle value, then keep only the half that can contain it.
  2. The list must be sorted, or the discarded half might hold the target.
  3. Each step halves the range, so the time is O(log n).
  4. bisect.bisect_left gives the same position from the standard library.

इसका उपयोग कब करें?

  • Algorithms और data structures की कार्यप्रणाली समझें।
  • हर चरण देखें और edge cases जाँचें।
  • समय और memory की जटिलता की तुलना करें।

Python में Binary Search Visualizer

O(log n)

हर comparison और data movement देखने के लिए चलाएँ या अगला चरण दबाएँ।

उदाहरण कोड

कोड चलाएँ →
main.py
def binary_search(values, target):
    low, high = 0, len(values) - 1
    while low <= high:
        middle = (low + high) // 2
        if values[middle] == target:
            return middle
        if values[middle] < target:
            low = middle + 1
        else:
            high = middle - 1
    return -1

print(binary_search([3, 8, 12, 17, 25, 31], 17))
इस उदाहरण के लिए Run बटन बनाएँ

अपेक्षित आउटपुट

3

यह कैसे काम करता है

Middle value तय करता है कि कौन-सा आधा भाग रखना है। समय O(log n) है और input sorted होना चाहिए।

मान बदलें और Python इंस्टॉल किए बिना CodeUtility ऑनलाइन Python कंपाइलर में प्रोग्राम चलाएँ।

अभ्यास के कार्य

बड़े dataset पर जाने से पहले input बदलें और edge cases की जाँच करें।

  1. खाली input, एक element और duplicate values जाँचें।
  2. हर चरण के बाद state दिखाएँ।
  3. Performance को दूसरे solution से तुलना करें।
Python IDE में चलाएँ →

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज