简单算法之二分查找
程序员文章站
2022-03-08 23:28:28
...
package com.chasen;
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {1, 10, 2, 5, 8, 18, 30};
int number = 2;
int index = binarySearch(arr, number);
System.out.println(index);
}
private static int binarySearch(int[] arr, int number) {
int min = 0;
int max = arr.length - 1;
while (min <= max) {
int mid = (min + max) >> 1;
if (arr[mid] > number) {
max = mid - 1;
} else if (arr[mid] < number) {
min = mid + 1;
} else {
return mid;
}
}
return -1;
}
}
上一篇: 函数的扩展、字符串的扩展方法和正则的扩展
下一篇: three.js创建场景实例详解