Binary Search

简介: 二分查找(Binary Search)是一种在有序数组中查找目标值的算法。它的基本思想是将数组分成两半,判断目标值是否在左半部分或右半部分,然后递归地在相应的半部分中查找。这个过程不断重复,直到找到目标值或者确定目标值不存在为止。二分查找的时间复杂度为 O(logn),其中 n 是数组的长度。

二分查找(Binary Search)是一种在有序数组中查找目标值的算法。它的基本思想是将数组分成两半,判断目标值是否在左半部分或右半部分,然后递归地在相应的半部分中查找。这个过程不断重复,直到找到目标值或者确定目标值不存在为止。二分查找的时间复杂度为 O(logn),其中 n 是数组的长度。
使用二分查找的条件是:数组是有序的,且数组元素具有比较运算符。
场景案例:

  1. 在一个电话号码簿中查找某个人的电话号码。
  2. 在一个有序的文件列表中查找某个文件。
  3. 在一个数据库中根据某个关键字查找记录。
    Demo:

示例代码

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

示例数组

arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

示例目标值

target = 13

调用二分查找函数

result = binary_search(arr, target)

输出结果

if result != -1:
print(f"元素 {target} 在数组中的索引为 {result}")
else:
print(f"元素 {target} 不在数组中")
CopyCopy

在这个示例中,我们定义了一个名为 binary_search 的函数,它接受一个有序数组 arr 和一个目标值 target。函数通过二分查找算法在数组中查找目标值,如果找到,则返回目标值在数组中的索引;如果没有找到,则返回 -1。

目录
相关文章
|
2月前
|
算法 索引
Binary Search
Binary Search “【5月更文挑战第21天】”
31 5
|
2月前
C. Binary Search
C. Binary Search
|
算法 Python
Leetcode-Medium 98. Validate Binary Search Tree
Leetcode-Medium 98. Validate Binary Search Tree
114 0
【1043】Is It a Binary Search Tree (25 分)
【1043】Is It a Binary Search Tree (25 分) 【1043】Is It a Binary Search Tree (25 分)
109 0
【1064】Complete Binary Search Tree (30 分)
【1064】Complete Binary Search Tree (30 分) 【1064】Complete Binary Search Tree (30 分)
88 0
|
机器学习/深度学习
1064. Complete Binary Search Tree (30)
#include #include #include using namespace std; const int maxn = 1001; vector num(maxn), cbt(maxn); int n, c...
831 0
|
算法 索引 C++
|
索引
leetcode Binary Search
leetcode 35 Search Insert Position Question Given a sorted array and a target value, return the index if the target is found.
1057 0
Binary Search Tree Iterator
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
578 0