அல்கோரிதம்basics

Binary Search அடிப்படைகள் — மாணவர்களுக்கு

TT
Testlaa Team
May 14, 20261 min read

Binary search என்பது magic அல்ல: விடைகள் order-ஆ அமைந்திருக்கும் போது மட்டுமே வேலை செய்யும். lo, hi borders வைத்து நடுவைப் பார்த்து, பதில் இருக்க முடியாத பாதியை நீக்குவோம்.

Try this in Python

def binary_search_exists(sorted_arr: list[int], target: int) -> bool:
    lo, hi = 0, len(sorted_arr) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        v = sorted_arr[mid]
        if v == target:
            return True
        if v < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return False


print(binary_search_exists([1, 3, 5, 9, 11], 9))

Key takeaways

  • sort order (அல்லது monotone predicate) தேவை.
  • while lo <= hi style ஒன்றைத் தேர்ந்து consistent ஆக இருங்கள்.
  • Python-இல் (lo + hi) // 2 போதுமானது.

Tags:

Binary searchPythonமாணவர்கள்