回答

收藏

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

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

可以使用以下代码实现二分查找算法:

% A( `5 h( g# N4 A* F5 f% q. o# i
  1. public class BinarySearch {
  2.     public static int binarySearch(int[] arr, int target) { 5 d1 G" n& {; U9 U. j' r
  3.         int left = 0; " f: J. N6 z2 x
  4.         int right = arr.length - 1;
  5.          & c4 A  v8 E! n1 ]
  6.         while (left <= right) {
  7.             int mid = left + (right - left) / 2; $ w* X* i& ~3 |; W+ w4 A1 M7 _
  8.              & @- }, {  q4 G, Y+ r
  9.             if (arr[mid] == target) {
  10.                 return mid; 6 _6 C: u& a( t0 V# E, o
  11.             } 1 S+ B- B6 T* U" D
  12.              ) p/ [6 d2 [  G+ m8 _
  13.             if (arr[mid] < target) {
  14.                 left = mid + 1; ) H' S, v+ U' E& Y" [
  15.             } else { 5 V+ P1 [. n5 G6 E, V) `
  16.                 right = mid - 1;
  17.             }
  18.         }
  19.         
  20.         return -1; % W, L8 G' M, f; P* o% p& s5 _
  21.     }
  22.     ) s/ T- w) Z& w8 H4 e& j- b: {
  23.     public static void main(String[] args) { 9 Z# s2 i0 T1 W" l  G* L
  24.         int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 3 K& _. i7 k0 W' Z9 z
  25.         int target = 6;
  26.          7 R5 Y+ Z0 {, t. W
  27.         int result = binarySearch(arr, target);
  28.          , C& ^. g+ @, v* [. `2 q4 f8 J% ?
  29.         if (result == -1) { " R; I+ G/ s5 k
  30.             System.out.println("Element not present in array"); 9 Y( E. x, D0 u9 u7 |2 Q
  31.         } else {
  32.             System.out.println("Element found at index " + result);
  33.         } - b/ t1 k4 w- b4 y/ s6 f# V
  34.     } - v6 V  @. e3 A/ j  U
  35. }
复制代码
这是一个简单的二分查找算法的实现,可以在给定的有序整数数组中查找目标元素的索引。
& 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
关注下面的标签,发现更多相似文章
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则