代码改变世界

拆半查找算法

2022-05-13 16:58  钟铧若岩  阅读(31)  评论(0编辑  收藏  举报

 

 1 package com.company;
 2 
 3 import org.junit.Test;
 4 
 5 public class BinarySearchNonRecursive {
 6 
 7     private static int binarySearch(int[] arr, int target) {
 8         int left = 0;
 9         int right = arr.length - 1;
10         while (left <= right) {
11             int mid = (left + right) / 2;
12             if (arr[mid] == target) {
13                 return mid;
14             } else if (arr[mid] > target) {
15                 right = mid - 1; // 向左找
16             } else {
17                 left = mid + 1; // 向右找
18             }
19         }
20         return -1;
21     }
22 
23  
24     @Test
25     public void main() {
26         int[] arr = {1, 3, 8, 10, 11, 67, 100};
27         int index = binarySearch(arr, 67);
28         if (index != -1) {
29             System.out.println("找到了,下标为:" + index);
30         } else {
31             System.out.println("没有找到--");
32         }
33     }
34 
35 
36 }