在有序数组查找特定元素
java
复制代码
/**
* 二分查找
* 对有序的数组,查找某个元素所在位置
*/
public class Code1_BinarySearch {
public static void main(String[] args) {
int[] arr = {1, 3, 5};
System.out.println(query(arr, 6));
System.out.println(query(arr, 1));
System.out.println(query(arr, 3));
}
/**
* 二分查找
* @param arr 有序数组
* @param n 查找元素
* @return 返回位置
*/
public static int query(int[] arr, int n) {
if (arr == null || arr.length < 1) {
return -1;
}
int l = 0;
int r = arr.length - 1;
while (l <= r) {
int m = (l+r) / 2;
if (arr[m] == n) {
return m;
} else if (arr[m] < n) {
l = m + 1;
} else {
r = m - 1;
}
}
return -1;
}
}
在有序数组查找 >= n 的最左侧位置
java
复制代码
/**
* 在有序数组查找 >= n 的最左侧位置
* 基于二分查找算法实现
*/
public class Code2_BinarySearchGrateLeft {
public static void main(String[] args) {
System.out.println(binarySearchGl(new int[]{6, 9, 10},1));
System.out.println(binarySearchGl(new int[]{6, 9, 10},6));
System.out.println(binarySearchGl(new int[]{6, 9, 10},9));
System.out.println(binarySearchGl(new int[]{6, 9, 10},10));
System.out.println(binarySearchGl(new int[]{6, 9, 10},11));
}
//数组没有>=n的元素返回-1,有则返回>=n的最左侧值
public static int binarySearchGl(int[] arr, int n) {
int l = 0;
int r = arr.length - 1;
int t = -1;
while (l <= r) {
int m = (l + r) / 2;
if (arr[m] < n) {
l = m + 1;
} else if (arr[m] >= n) {
r=m-1;
t=m;
}
}
return t;
}
}
有一个无序的数组,相邻元素不重复,在这个数组查找一个局部最小值
java
复制代码
/**
* 有一个无序的数组,相邻元素不重复,在这个数组查找一个局部最小值
*/
public class Code3_LocalOneMinSearch {
public static void main(String[] args) {
// System.out.println(search(new int[]{1,2,3}));
// System.out.println(search(new int[]{3,2,1}));
// System.out.println(search(new int[]{3}));
System.out.println(search(new int[]{10,5,7,61,100}));
}
public static int search(int[] arr) {
if (arr == null || arr.length == 0) {
return -1;
}
int len = arr.length;
if (len == 1) {
return 0;
}
if(arr[0]<arr[1]){
return 0;
}
if(arr[len-1]<arr[len-2]){
return len-1;
}
int l=0;
int r=len-1;
while (l<r-1){
int m=(l+r)/2;
if(arr[m]<arr[m-1] && arr[m]<arr[m+1]){
return m;
}
if(arr[m]>arr[m-1]){
r=m-1;
}
if(arr[m]>arr[m+1]){
l=m+1;
}
}
return arr[l]<arr[r]?l:r;
}
}