🧑💻 算法学习 · Binary Search
二分查找 (Binary Search)
概述
难度:简单 (Easy)
分类:Search / 查找
二分查找是一种在有序数组中查找目标元素的搜索算法。
Binary search is a search algorithm that finds the position of a target value within a sorted array.
算法原理
中文:通过比较数组中间元素与目标值,每次将搜索范围缩小一半。
English: By comparing the middle element with the target, the search range is halved each time.
复杂度分析
| 类型 | 复杂度 |
|---|---|
| 时间复杂度 | O(log n) |
| 空间复杂度 | O(1) |
代码实现
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
每日练习
- 完成算法实现
- 分析算法复杂度
- 思考:算法的适用场景和局限性
相关阅读:算法专栏
💡 学习建议:算法学习重在理解思想,多写多练是关键。 💡 Learning tip: Algorithm learning is about understanding the core idea. Practice makes perfect.