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.
आप क्या सीखेंगे
- 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
Halve the range every step
Binary search हर comparison के बाद search range को आधा कर देता है।
मुख्य बातें
- Compare the target with the middle value, then keep only the half that can contain it.
- The list must be sorted, or the discarded half might hold the target.
- Each step halves the range, so the time is
O(log n). bisect.bisect_leftgives 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))
अपेक्षित आउटपुट
3
यह कैसे काम करता है
Middle value तय करता है कि कौन-सा आधा भाग रखना है। समय O(log n) है और input sorted होना चाहिए।
मान बदलें और Python इंस्टॉल किए बिना CodeUtility ऑनलाइन Python कंपाइलर में प्रोग्राम चलाएँ।
अभ्यास के कार्य
बड़े dataset पर जाने से पहले input बदलें और edge cases की जाँच करें।
- खाली input, एक element और duplicate values जाँचें।
- हर चरण के बाद state दिखाएँ।
- Performance को दूसरे solution से तुलना करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
- फैक्ट्री उत्पादन समय पैरेलल मशीनें किसी लक्ष्य संख्या की वस्तुएँ सबसे जल्दी कब पूरी कर सकती हैं, यह ज्ञात करें। मध्यम
- Median of Two Sorted Arrays Find the median of two sorted lists combined. कठिन