---
# System prepended metadata

title: Binary Search

---

# Binary Search

二分搜：
```cpp=
class Solution {
public:
    int search(vector<int>& nums, int target) {
        int r = 0;
        int l = nums.size()-1;
        int mid = (l+r) / 2;
        while (r <= l) {
            if (nums[mid] == target) return mid;
            if (target > nums[mid]) r = mid + 1;
            if (target < nums[mid]) l = mid - 1;
            mid = (r+l) / 2;
        }
        return -1;
    }
};
```
![](https://i.imgur.com/wgMoeS7.png)

<br>

線性搜尋：
```cpp=
class Solution {
public:
    int search(vector<int>& nums, int target) {
       
        for(int i=0;i<(int)nums.size(); i++){
            if(nums[i] == target) return i;
        }
        
        return -1;
        
    }
};
```
![](https://i.imgur.com/RgaQIIb.png)

<br>
<br>
<br>

# Sort an Array
```cpp=
class Solution {
public:
    int search(vector<int>& nums, int target) {
       
        for(int i=0;i<(int)nums.size(); i++){
            if(nums[i] == target) return i;
        }
        return -1;
    }
};
```
![](https://i.imgur.com/rWiLNf7.png)

泡泡 選擇 插入 合併