怎么用编程实现二分查找

时间:2025-01-28 14:08:36 网络游戏

二分查找是一种高效的查找算法,适用于有序数组。其基本思想是每次将查找范围缩小一半,直到找到目标元素或确定目标元素不存在。以下是使用不同编程语言实现二分查找的示例代码:

C++

```cpp

include

include

int binarySearch(const std::vector& 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 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 in the array." << std::endl;

}

return 0;

}

```

Java

```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 in the array.");

}

}

}

```

Python

```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

示例用法

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

target = 4

result = binary_search(arr, target)

if result != -1:

print(f"Element found at index: {result}")

else:

print("Element not found in the array.")

```

JavaScript

```javascript

function binarySearch(arr, target) {

let left = 0;

let right = arr.length - 1;

while (left <= right) {

let mid = Math.floor(left + (right - left) / 2);

if (arr[mid] === target) {

return mid;

} else if (arr[mid] < target) {

left = mid + 1;

} else {

right = mid - 1;

}

}

return -1;

}

// 示例用法

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

let target = 4;

let result = binarySearch(arr, target);

if (result !== -1) {

console.log(`Element found at index: ${result}`);

} else {

console.log("Element not found in the array.");

}

```

总结

以上示例展示了