6

二分查找及其变形

 2 years ago
source link: https://stellarx.github.io/post/58043ebd.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
花 风 城市

二分查找及其变形

发表于2022-04-17|更新于2022-04-19|算法与数据结构
字数总计:320|阅读时长:1分钟|阅读量:4

Java实现

public class BinarySearch {
public static void main(String[] args) {
int[] array = new int[]{1, 3, 5, 7, 9, 11, 19};
// System.out.println(binarySearch(array, 19));
System.out.println(binarySearchGE(array, 2));
// System.out.println(binarySearchLE(array, 0));
}

public static int binarySearch(int[] arr, int k) {
int f = 0, b = arr.length - 1, mid;
while (f <= b) {
mid = f + (b - f) / 2;//这样计算可以防止数据溢出
if (k == arr[mid]) return mid;
if (k < arr[mid]) b = mid - 1;
else if (k > arr[mid]) f = mid + 1;
}
return -1;
}

/**
* 查找第一个>=目标值的数 注意,目标数不一定出现在数组中
*/
public static int binarySearchGE(int[] arr, int target){
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
System.out.println(left + " " + mid + " " + right);
if (target > arr[mid]) left = mid + 1;//如果是查第一个>目标值的数,只需要改成target >= arr[mid]
else right = mid - 1;
}
if (left > arr.length - 1) return -1;
return left;
}

/**
* 查找第一个<=目标值的数 注意,目标数不一定出现在数组中
*/
public static int binarySearchLE(int[] arr, int target){
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
System.out.println(left + " " + mid + " " + right);
if (target < arr[mid]) right = mid - 1;//如果是查第一个<目标值的数,只需要改成target <= arr[mid]
else left = mid + 1;
}
return right;
}
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK