> For the complete documentation index, see [llms.txt](https://zcjian.gitbook.io/project/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zcjian.gitbook.io/project/array/binary-search.md).

# Binary Search

```python
def search(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: int
    """
    high = len(nums)-1
    low = 0
    firstRes = -1
    # 要 low <= high 夾擠夾到, 若只有 < 出錯高達95%
    while low <= high:
        # mid = (high + low) // 2 : not recommended (overflow issue)

        mid = low + (high-low)//2
        if nums[mid] == target:
            firstRes = mid
            high = mid -1

        elif target < nums[mid]:
            high = mid - 1
        else:
            low = mid + 1
    """
    memo = []
    while 0 <= firstRes < len(nums) and target == nums[firstRes]:
        memo.append(firstRes)
    return memo
    """
    return firstRes
search([-1,0,3,5,9,12], 9)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zcjian.gitbook.io/project/array/binary-search.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
