可以使用以下代码实现二分查找算法: ; {% A1 ~5 B4 Y3 Z/ U( Y( N' d& V
- public class BinarySearch {
1 f* \; ]$ `: _/ `! A( `! j; R0 j! c
- public static int binarySearch(int[] arr, int target) {
- int left = 0;
: b0 T" D5 z& z. {" M
- int right = arr.length - 1;
-
# k9 J- L' Q/ I" x# p
- while (left <= right) {
- int mid = left + (right - left) / 2;
-
- if (arr[mid] == target) {
( k- e1 d @% V" V
- return mid;
- }
-
1 p% f {- i) ]2 X
- if (arr[mid] < target) {
, t, i6 K+ Y% x. m
- left = mid + 1;
- } else {
& L9 D/ s7 G( K( P: W
- right = mid - 1;
: }3 G6 E( `5 D- L
- }
- }
0 r2 c$ f* I, b/ m1 H( [( x m
-
% s$ j1 q o- W8 q( q0 L. E3 O$ n
- return -1;
$ H$ Q0 [' ?) b
- }
-
- public static void main(String[] args) {
, J3 N' F3 k3 e! |1 [
- int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
8 ^4 }- {# \( d* J# d4 }
- int target = 6;
-
- int result = binarySearch(arr, target);
: h. J! _2 i. Q1 u
-
' _$ I8 a* H9 {+ E& w( S& v- R
- if (result == -1) {
: O0 `. e1 o) I6 m& ~0 F" y1 z. @) p+ H
- System.out.println("Element not present in array");
/ z. L& h% V( V# X5 a$ [
- } else {
: |6 k: F% s; b3 B- y
- System.out.println("Element found at index " + result);
3 n# v: b5 s9 [) I
- }
- }
- }
5 D9 d& D( o3 m6 V6 o0 q( C6 V
复制代码
这是一个简单的二分查找算法的实现,可以在给定的有序整数数组中查找目标元素的索引。
% k1 \8 I/ e/ x( p7 B7 f+ N5 j
. q5 d/ A9 D. [' T+ c% U8 g6 y
$ A+ a9 H8 z: w7 C |