அல்கோரிதம்array binary search

Array Binary Search மாறுபாடுகள்

TT
Testlaa Team
May 14, 20261 min read

Rotated array, duplicates, இரண்டு list-களில் virtual array — twistகள் வரும். இருந்தாலும் search space-ன் monotone பகுதியில் binary search.

Try this in Python

def search_rotated(nums: list[int], target: int) -> bool:
    """Classic pattern sketch: one half is always normally sorted."""
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return True
        # Students: finish cases by comparing endpoints; this is a template stub.
        if nums[lo] <= nums[mid]:  # left half sorted
            if nums[lo] <= target < nums[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        else:
            if nums[mid] < target <= nums[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
    return False


print(search_rotated([4, 5, 6, 7, 0, 1, 2], 0))

Key takeaways

  • எந்த பக்கம் sorted என்பதைக் கண்டுபிடி.
  • Duplicates இருக்கும்போது boundaries கவனமாக.
  • முதலில் classic search பயிற்சி.

Tags:

Binary searchPythonமாணவர்கள்