shz.core.alg.search.BinarySearcher Maven / Gradle / Ivy
package shz.core.alg.search;
public final class BinarySearcher {
private BinarySearcher() {
throw new IllegalStateException();
}
/**
* 二分查找,数组a为升序数组
* 时间复杂度:log2(n)
*
* @return 返回key在数组a中的索引
*/
public static int search(int[] a, int k) {
int lo = 0, hi = a.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (k < a[mid]) hi = mid - 1;
else if (k > a[mid]) lo = mid + 1;
else return mid;
}
return -1;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy