public class BinarySearch {
/**
* 二分查找基础班
* [i,j]
*/
public static int binarySearchBasic1(int[] a, int target) {
int i = 0;
int j = a.length - 1;
while (i <= j) {
int m = (i + j) >>> 1;
if (target < a[m]) {
j = m - 1;
} else if (target > a[m]) {
i = m + 1;
} else {
return m;
}
}
return -1;
}
/**
* 二分查找升级版
* [i,j)
* j指向查找的边界,不是查找目标
*/
public static int binarySearchBasicUpgrades(int[] a, int target) {
int i = 0;
int j = a.length;
while (i < j) {
int m = (i + j) >>> 1;
if (target < a[m]) {
j = m;
} else if (a[m] < target) {
i = m + 1;
} else {
return m;
}
}
return -1;
}
/**
* 二分查找平衡版
* [i,j)
* j指向查找的边界,不是查找目标
* while循环结束后在判断
*/
public static int binarySearchBasicBalance(int[] a, int target) {
int i = 0;
int j = a.length;
while (1 < j - i) {
int m = (i + j) >>> 1;
if (target < a[m]) {
j = m;
} else {
i = m;
}
}
if (a[i] == target) {
return i;
} else {
return -1;
}
}
/**
* 二分查找如果有重复元素返回最右侧的索引
* 找不到返回-1
*/
public static int binarySearchBasicRightmost(int[] a, int target) {
int i = 0;
int j = a.length - 1;
int candidate = -1;
while (i <= j) {
int m = (i + j) >>> 1;
if (target < a[m]) {
j = m - 1;
} else if (a[m] < target) {
i = m + 1;
} else {
candidate = m;
i = m + 1;
}
}
return candidate;
}
/**
* 二分查找
* 如果有重复元素
* 返回 >= target 最右侧的索引
*/
public static int binarySearchBasicRightmostUpgrades(int[] a, int target) {
int i = 0;
int j = a.length - 1;
while (i <= j) {
int m = (i + j) >>> 1;
if (target < a[m]) {
j = m - 1;
} else {
i = m + 1;
}
}
return i - 1;
}
/**
* 二分查找如果有重复元素返回最左侧的索引
* 找不到返回-1
*/
public static int binarySearchBasicLeftmost(int[] a, int target) {
int i = 0;
int j = a.length - 1;
int candidate = -1;
while (i <= j) {
int m = (i + j) >>> 1;
if (target < a[m]) {
j = m - 1;
} else if (a[m] < target) {
i = m + 1;
} else {
candidate = m;
j = m - 1;
}
}
return candidate;
}
/**
* 二分查找
* 如果有重复元素
* 返回 >= target 最左侧的索引
*/
public static int binarySearchBasicLeftmostUpgrades(int[] a, int target) {
int i = 0;
int j = a.length - 1;
while (i <= j) {
int m = (i + j) >>> 1;
if (target <= a[m]) {
j = m - 1;
} else {
i = m + 1;
}
}
return i;
}
}
Java 二分查找
最新推荐文章于 2024-10-10 15:47:02 发布
本文详细介绍了Java中的二分查找算法的五种实现:基本版、升级版、平衡版,以及针对有重复元素时寻找最右侧和最左侧索引的方法。
摘要由CSDN通过智能技术生成