【Py/Java/C++三种语言OD独家2024D卷真题】20天拿下华为OD笔试之【二分查找】2024D-机器人搬砖【欧弟算法】全网注释最详细分类最全的华为OD真题题解
二分查找算法通常用于在有序数组中查找特定元素。以下是使用Python、Java和C++实现的二分查找算法的示例代码。
Python:
def binary_search(arr, x):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
return mid
elif arr[mid] > x:
high = mid - 1
else:
low = mid + 1
return -1
# 示例使用
arr = [2, 3, 4, 10, 40]
x = 10
# 函数调用
result = binary_search(arr, x)
print(result) # 输出元素的索引,未找到返回-1
Java:
public class BinarySearch {
public static int binarySearch(int[] arr, int x) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] > x) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
// 示例使用
public static void main(String[] args) {
int[] arr = {2, 3, 4, 10, 40};
int x = 10;
// 函数调用
int result = binarySearch(arr, x);
System.out.println(result); // 输出元素的索引,未找到返回-1
}
}
C++:
#include <iostream>
#include <vector>
int binarySearch(const std::vector<int>& arr, int x) {
int low = 0;
int high = arr.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] > x) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
int main() {
std::vector<int> arr = {2, 3, 4, 10, 40};
int x = 10;
// 函数调用
int result = binarySearch(arr, x);
std::cout << result << std::endl; // 输出元素的索引,未找到返回-1
return 0;
}
以上代码实现了二分查找算法,在有序数组中查找特定元素的索引。如果找到,返回元素的索引;如果未找到,返回-1。
评论已关闭