Binary Search 二元搜尋法
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
二元搜尋法,也就是將排序好的資料分割成兩等份。每次挑出一個數字,和中間值比較,判斷目標在前半或後半。然後再進行二元分割。它的時間複雜度是 。
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
一、步驟觀察
- 找出中間值
- 如果目標值 === 中間值,則傳回 index
- 如果目標值 > 中間值,則從右邊子陣列找,重複步驟一 (recur for the right half)
- 如果目標值 < 中間值,則從左邊子陣列找,重複步驟一 (recur for the left half)
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
( 圖片來源 wiki )
二、實際操作
使用哪種資料結構:Array
- x 為目標
- 將 left l 和 right r 作為陣列兩端的索引值
- 如果 r > l,可以二分的情況
- 將 x 與中間位置 middle 的值做比較
- 如果 x > arr[middle],呼叫 binarySearch() 處理右邊陣列
- 如果 x < arr[middle],呼叫 binarySearch() 處理左邊陣列
- 如果 x === arr[middle],回傳 middle
- 回傳 -1,代表沒有相對應的值
邏輯:
程式碼實作:
三、時間複雜度 Big O
資料來源