package com.lmh.test.algorithm.binarysearch;
/**
* 二分查找
* @author BestHeaker
* @date 2021/12/28
* @time 21:42
*/
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7,8};
int low = 0;
int high = 7;
int target = 8;
int i = BinarySearch.binarySearch(arr, low, high, target);
System.out.print("选择的数下标为:"+i);
}
private static int binarySearch(int[] s, int low, int high, int target) {
while (low <= high) {
int middle = (low + high) / 2;
if (target == s[middle]) {
return middle;
} else if (target > s[middle]) {
low = middle + 1;
} else if (target < s[middle]) {
high = middle - 1;
}
}
return -1;
}
}
二分查找(通俗易懂)
最新推荐文章于 2024-10-12 17:55:45 发布