可以使用以下代码实现二分查找算法:
% A( `5 h( g# N4 A* F5 f% q. o# i
- public class BinarySearch {
- public static int binarySearch(int[] arr, int target) {
5 d1 G" n& {; U9 U. j' r
- int left = 0;
" f: J. N6 z2 x
- int right = arr.length - 1;
-
& c4 A v8 E! n1 ]
- while (left <= right) {
- int mid = left + (right - left) / 2;
$ w* X* i& ~3 |; W+ w4 A1 M7 _
-
& @- }, { q4 G, Y+ r
- if (arr[mid] == target) {
- return mid;
6 _6 C: u& a( t0 V# E, o
- }
1 S+ B- B6 T* U" D
-
) p/ [6 d2 [ G+ m8 _
- if (arr[mid] < target) {
- left = mid + 1;
) H' S, v+ U' E& Y" [
- } else {
5 V+ P1 [. n5 G6 E, V) `
- right = mid - 1;
- }
- }
-
- return -1;
% W, L8 G' M, f; P* o% p& s5 _
- }
-
) s/ T- w) Z& w8 H4 e& j- b: {
- public static void main(String[] args) {
9 Z# s2 i0 T1 W" l G* L
- int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
3 K& _. i7 k0 W' Z9 z
- int target = 6;
-
7 R5 Y+ Z0 {, t. W
- int result = binarySearch(arr, target);
-
, C& ^. g+ @, v* [. `2 q4 f8 J% ?
- if (result == -1) {
" R; I+ G/ s5 k
- System.out.println("Element not present in array");
9 Y( E. x, D0 u9 u7 |2 Q
- } else {
- System.out.println("Element found at index " + result);
- }
- b/ t1 k4 w- b4 y/ s6 f# V
- }
- v6 V @. e3 A/ j U
- }
复制代码
这是一个简单的二分查找算法的实现,可以在给定的有序整数数组中查找目标元素的索引。
& t4 K& B; z$ a- c f. _4 @3 ^3 x) M+ a- }$ {1 u7 c7 K
H- t) X1 r+ ]! n: J4 Q3 j |