可以使用以下代码实现二分查找算法: 4 i( @0 W. r! }9 }. X
- public class BinarySearch {
7 G6 ]9 h# L0 y0 F V. v. E7 D- N
- 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;
# R. i4 G3 P2 A; S3 D( P9 R
-
- if (arr[mid] == target) {
- V, F" L+ t1 t1 k7 B0 S9 {
- return mid;
2 a% r8 z5 V+ [$ [# t
- }
% c: y- y9 \; s# b7 f3 k& d
-
- if (arr[mid] < target) {
" d' T8 @0 _$ R# @
- left = mid + 1;
9 H b e; E8 i; R+ `
- } else {
- right = mid - 1;
3 H0 T; S0 q0 u1 e; b& ?: W
- }
- }
, f- p+ }6 o: N& h5 o3 F9 G
-
. d G Y( |2 j. K9 y
- return -1;
- }
" \/ ?, F( P6 D9 E
-
- public static void main(String[] args) {
7 X4 q; u, O/ O8 g
- int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- int target = 6;
-
( e9 w# h' ^3 e$ e/ @
- int result = binarySearch(arr, target);
-
' L! l1 }4 O% A! [
- if (result == -1) {
4 T4 x/ v$ b: B3 D5 G& K. L- I2 y
- System.out.println("Element not present in array");
- } else {
- System.out.println("Element found at index " + result);
- }
- }
- }
2 i+ d) E- z' v$ V; R/ {, q
复制代码
这是一个简单的二分查找算法的实现,可以在给定的有序整数数组中查找目标元素的索引。# {9 w" ]% g& w5 ^4 O
! Y* \ K) l1 t3 Z
7 U4 \, E" h8 w; n9 F |