运行 ❯
获取您
自己的
网站
×
更改方向
更改主题,深色/浅色
转到空间
Python
C
Java
def binarySearch(arr, targetVal): left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == targetVal: return mid if arr[mid] < targetVal: left = mid + 1 else: right = mid - 1 return -1 myArray = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] myTarget = 15 result = binarySearch(myArray, myTarget) if result != -1: print("Value",myTarget,"found at index", result) else: print("Target not found in array.") #Python
#include <stdio.h> int binarySearch(int arr[], int size, int targetVal); int main() { int myArray[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}; int myTarget = 15; int size = sizeof(myArray) / sizeof(myArray[0]); int result = binarySearch(myArray, size, myTarget); if (result != -1) { printf("Value %d found at index %d\n", myTarget, result); } else { printf("Target not found in array.\n"); } return 0; } int binarySearch(int arr[], int size, int targetVal) { int left = 0; int right = size - 1; while (left <= right) { int mid = (left + right) / 2; if (arr[mid] == targetVal) { return mid; } if (arr[mid] < targetVal) { left = mid + 1; } else { right = mid - 1; } } return -1; } //C
public class Main { public static void main(String[] args) { int[] myArray = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}; int myTarget = 15; int result = binarySearch(myArray, myTarget); if (result != -1) { System.out.println("Value " + myTarget + " found at index " + result); } else { System.out.println("Target not found in array."); } } public static int binarySearch(int[] arr, int targetVal) { int left = 0; int right = arr.length - 1; while (left <= right) { int mid = (left + right) / 2; if (arr[mid] == targetVal) { return mid; } if (arr[mid] < targetVal) { left = mid + 1; } else { right = mid - 1; } } return -1; } } //Java
Python 结果
C 结果
Java 结果
在索引 7 处找到值 15
在索引 7 处找到值 15
在索引 7 处找到值 15