public class BSearchUtils {
/**
* 二分查找
*/
public static void boundarySearch(int[] a, int n, int value) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] == value) {
Log.d("zpb", "find index=" + mid);
return;
}
if (a[mid] > value) {
high = mid - 1;
} else {
low = mid + 1;
}
}
Log.d("zpb", "not find ");
}
/**
* 搜寻第一个和查找值相等的值
* @param a
* @param n
* @param value
*/
public static void boundaryFirstSearch(int[] a, int n, int value) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] > value) {
high = mid - 1;
} else if (a[mid] < value) {
low = mid + 1;
} else {
if (mid == 0 || a[mid - 1] < value) {
Log.d("zpb", "has find=" + mid);
return;
}
high = mid - 1;
}
}
Log.d("zpb", "not find");
}
/**
* 查找最后一个复合条件的数值
* @param a
* @param n
* @param value
*/
public static void boundaryLastSearch(int[] a, int n, int value) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] > value) {
high = mid - 1;
} else if (a[mid] < value) {
low = mid + 1;
} else {
if (mid == n - 1 || a[mid + 1] > value) {
Log.d("zpb", "find index=" + mid);
return;
}
low = mid + 1;
}
}
}
/**
* 查找第一个大于等于给定值的数
* @param a
* @param n
* @param value
*/
public static void boundaryFirstMaxSearch(int[] a, int n, int value) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] >= value) {
// 判断钱一个数值是否也是《=
if (mid == 0 || a[mid - 1] < value) {
Log.d("zpb", "has find=" + mid);
return;
}
high = mid - 1;
} else {
low = mid + 1;
}
}
}
/**
* 查找最后一个小于等于给定值
* @param a
* @param n
* @param value
*/
public static void boundaryLastMin(int[] a, int n, int value) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] <= value) {
if (mid == n - 1 || a[mid + 1] > value) {
Log.d("zpb", "has find index=" + mid);
return;
}
low = mid + 1;
} else {
high = mid - 1;
}
}
}
}