C++,Java,Python,Javascript实现二分查找算法
二分查找算法是一种在有序数组中查找特定元素的搜索算法。它的基本思想是将数组分成两半,通过比较中间元素与目标值来决定是在左半部分还是右半部分继续查找,从而逐步缩小查找范围直到找到目标值或者确定目标值不存在于数组中。
下面是使用 C++、Java、Python 和 JavaScript 实现二分查找算法的示例代码:
C++
#include <iostream>
#include <vector>
int binarySearch(const std::vector<int>& arr, int target) {
int left = 0;
int right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // 找到目标值,返回其索引
} else if (arr[mid] < target) {
left = mid + 1; // 在右半部分查找
} else {
right = mid - 1; // 在左半部分查找
}
}
return -1; // 没有找到目标值
}
int main() {
std::vector<int> arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int target = 4;
int result = binarySearch(arr, target);
if (result != -1) {
std::cout << "Element found at index: " << result << std::endl;
} else {
std::cout << "Element not found" << std::endl;
}
return 0;
}
Java
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // 找到目标值,返回其索引
} else if (arr[mid] < target) {
left = mid + 1; // 在右半部分查找
} else {
right = mid - 1; // 在左半部分查找
}
}
return -1; // 没有找到目标值
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int target = 4;
int result = binarySearch(arr, target);
if (result != -1) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found");
}
}
}
Python
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 # 没有找到目标值
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 4
result = binary_search(arr, target)
if result != -1:
print("Element found at index:", result)
else:
print("Element not found")
JavaScript
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid; // 找到目标值,返回其索引
} else if (arr[mid] < target) {
left = mid + 1; // 在右半部分查找
} else {
right = mid - 1; // 在左半部分查找
}
}
return -1; // 没有找到目标值
}
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const target = 4;
const result = binarySearch(arr, target);
if (result !== -1) {
console.log(`Element found at index: ${result}`);
} else {
console.log('Element not found');
}
以上就是使用四种不同语言实现二分查找算法的例子。每种语言的实现逻辑都是相同的,但是语法上会有一些差异。希望这些例子对你有所帮助!
作者:ukyo--碳水化合物
出处:https://www.cnblogs.com/ukzq/p/18565454
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
2023-11-24 消费陷阱
2021-11-24 git 取消pull操作
2021-11-24 schema-redis-demo
2020-11-24 HTTP/2.0与HTTP/1.1协议区别
2020-11-24 什么是长连接
2019-11-24 关于树形菜单
2018-11-24 [微信开发] - 关于测试号以及消息发送及回复