回答

收藏

如何用java实现二分查找算法

知识点 知识点 1162 人阅读 | 0 人回复 | 2023-12-04

可以使用以下代码实现二分查找算法:
8 P6 k  X2 X" L; k
  1. public class BinarySearch {
  2.     public static int binarySearch(int[] arr, int target) {
  3.         int left = 0;
  4.         int right = arr.length - 1; , [5 ]- h0 D. Y! |! @
  5.         
  6.         while (left <= right) { 8 k/ Y4 Z4 c6 q$ ^0 M; N' R
  7.             int mid = left + (right - left) / 2; - d0 ]" M5 Q: @. E& M
  8.             
  9.             if (arr[mid] == target) { ) B( ~/ [  H: F6 X
  10.                 return mid;
  11.             }
  12.             
  13.             if (arr[mid] < target) { 4 ]4 N* O9 Z# N  l9 s
  14.                 left = mid + 1;   W$ P! t: q4 P8 ^+ n/ Z
  15.             } else { ) y: C2 d' M* v0 ~" V+ b) V
  16.                 right = mid - 1; 7 s/ l, R3 D. [- W: }
  17.             } 0 V% o# K6 j6 M& ]
  18.         } " r) u, l; J* o1 O- R
  19.         
  20.         return -1;
  21.     } ; q/ W( F! _( ]$ c" Q5 A
  22.     + X' N. V3 w% M2 i; b
  23.     public static void main(String[] args) {
  24.         int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  25.         int target = 6; ! `# Z  r2 H- F+ f8 o- p8 y. b
  26.          , S1 u' `3 c4 V- c' r7 @
  27.         int result = binarySearch(arr, target);
  28.         
  29.         if (result == -1) { # V0 e4 O& N( |  ]% \
  30.             System.out.println("Element not present in array");
  31.         } else { * u& ]) u0 _* J( G3 ?8 S; m3 @
  32.             System.out.println("Element found at index " + result);
  33.         } 2 J, C5 Z0 e# q  {, Z4 F' H# R
  34.     } ; ]$ t! }" Q0 L( M
  35. }
复制代码
这是一个简单的二分查找算法的实现,可以在给定的有序整数数组中查找目标元素的索引。2 t0 t- |: s+ l3 x

3 s8 K6 f% \8 o0 r3 I1 M# H# g" r, X
9 N$ i6 P. b7 a/ j
关注下面的标签,发现更多相似文章
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则