可以使用以下代码实现二分查找算法:
) l( g1 c' }+ r. L, `7 j
- public class BinarySearch {
4 N4 U+ `" W7 }0 W: A2 G4 ^, |: s
- public static int binarySearch(int[] arr, int target) {
- int left = 0;
8 N+ d, ^) B R" f% K3 G* ]) `+ | W
- int right = arr.length - 1;
9 v5 i; s2 ~4 j9 d
-
5 T$ H, z" ^1 o9 s, F3 S( D% i s
- while (left <= right) {
3 L( S, u% g; P
- int mid = left + (right - left) / 2;
-
- if (arr[mid] == target) {
' A6 g9 i3 ^9 {, T6 {
- return mid;
- }
- u' u& r$ n' l/ _ l) e- x! F3 w
-
7 U) Y; U; ^; V0 w7 u% R
- if (arr[mid] < target) {
& e3 v1 E5 a. I5 n1 L4 e
- left = mid + 1;
/ I0 o9 `- g' e3 `) ?$ u. x1 T
- } else {
) C! O4 N8 b1 Q2 A) z) c& M7 I
- right = mid - 1;
- }
6 B2 z0 W$ w7 u( Q& o' v
- }
-
; @% G" h8 o8 s+ @( E5 v, j o
- return -1;
" K! o! X4 r3 I: s5 j
- }
-
$ A" |! H) t1 ^5 M8 r4 R, K
- public static void main(String[] args) {
& O; f! J% c2 S& _
- int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
1 L5 w* I) M1 ]( ~, `
- int target = 6;
" C3 L" E; u X7 ~, L
-
- int result = binarySearch(arr, target);
-
0 [( K3 R0 j" ^) J6 H2 _+ V/ P
- if (result == -1) {
- System.out.println("Element not present in array");
7 }- \; C, T' T5 X' @1 `5 s: S
- } else {
- System.out.println("Element found at index " + result);
- }
$ G* f2 b' C" R' w5 F
- }
- }
4 n, O' |: m( S: v+ N) [2 |* f
复制代码
这是一个简单的二分查找算法的实现,可以在给定的有序整数数组中查找目标元素的索引。/ |. p1 c. L# R+ S" ]: c
. ?. M/ h9 f1 G) Q7 Y5 O
. a* O. a }& \# j! S |