二分探索(Binary Search)
C
#include <stdio.h>
int binarySearch(int arr[], int l, int r, int x) {
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x) {
return m;
}
if (arr[m] < x) {
l = m + 1;
} else {
r = m - 1;
}
}
return -1;
}
int main() {
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? printf("Element not found\n") : printf("Element found at index %d\n", result);
return 0;
}
C++
#include <iostream>
using namespace std;
int binarySearch(int arr[], int l, int r, int x) {
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x) {
return m;
}
if (arr[m] < x) {
l = m + 1;
} else {
r = m - 1;
}
}
return -1;
}
int main() {
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? cout << "Element not found" << endl : cout << "Element found at index " << result << endl;
return 0;
}
C#
using System;
class Program {
static int BinarySearch(int[] arr, int x) {
int l = 0, r = arr.Length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x) {
return m;
}
if (arr[m] < x) {
l = m + 1;
} else {
r = m - 1;
}
}
return -1;
}
static void Main() {
int[] arr = {2, 3, 4, 10, 40};
int x = 10;
int result = BinarySearch(arr, x);
Console.WriteLine(result == -1 ? "Element not found" : "Element found at index " + result);
}
}
Java
public class BinarySearch {
public static int binarySearch(int[] arr, int x) {
int l = 0, r = arr.length - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (arr[m] == x) {
return m;
}
if (arr[m] < x) {
l = m + 1;
} else {
r = m - 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 ? "Element not found" : "Element found at index " + result);
}
}
Python
def binary_search(arr, x):
l, r = 0, len(arr) - 1
while l <= r:
m = l + (r - l) // 2
if arr[m] == x:
return m
if arr[m] < x:
l = m + 1
else:
r = m - 1
return -1
arr = [2, 3, 4, 10, 40]
x = 10
result = binary_search(arr, x)
print("Element found at index" if result != -1 else "Element not found", result)
JavaScript
function binarySearch(arr, x) {
let l = 0, r = arr.length - 1;
while (l <= r) {
let m = l + Math.floor((r - l) / 2);
if (arr[m] === x) {
return m;
}
if (arr[m] < x) {
l = m + 1;
} else {
r = m - 1;
}
}
return -1;
}
const arr = [2, 3, 4, 10, 40];
const x = 10;
const result = binarySearch(arr, x);
console.log(result === -1 ? "Element not found" : "Element found at index " + result);
この記事が気に入ったらサポートをしてみませんか?