90 lines
2.1 KiB
Java
90 lines
2.1 KiB
Java
package search;
|
|
|
|
/**
|
|
* @author Nikita Doschennikov (me@fymio.us)
|
|
*/
|
|
public class BinarySearch3637 {
|
|
|
|
public static void main(String[] args) {
|
|
IntList a = new IntList();
|
|
int x = Integer.parseInt(args[0]);
|
|
int n = args.length;
|
|
for (int i = 1; i < n; i++) {
|
|
a.put(Integer.parseInt(args[i]));
|
|
}
|
|
System.out.println(rightBound(x, a) - leftBound(x, a));
|
|
}
|
|
|
|
static int leftBound(int x, IntList a) {
|
|
int low = 0,
|
|
high = a.getLength() - 1;
|
|
while (low <= high) {
|
|
int mid = low + (high - low) / 2;
|
|
if (a.get(mid) > x) {
|
|
low = mid + 1;
|
|
} else {
|
|
high = mid - 1;
|
|
}
|
|
}
|
|
return high + 1;
|
|
}
|
|
|
|
static int rightBound(int x, IntList a) {
|
|
int low = 0,
|
|
high = a.getLength() - 1;
|
|
while (low <= high) {
|
|
int mid = low + (high - low) / 2;
|
|
if (a.get(mid) >= x) {
|
|
low = mid + 1;
|
|
} else {
|
|
high = mid - 1;
|
|
}
|
|
}
|
|
return high + 1;
|
|
}
|
|
|
|
static int searchIterativeDecreasing(int x, IntList a) {
|
|
if (a.getLength() == 0) {
|
|
return 0;
|
|
}
|
|
|
|
int low = 0,
|
|
high = a.getLength() - 1;
|
|
|
|
while (low <= high) {
|
|
int mid = low + (high - low) / 2;
|
|
|
|
if (a.get(mid) <= x) {
|
|
high = mid - 1;
|
|
} else {
|
|
low = mid + 1;
|
|
}
|
|
}
|
|
|
|
return low;
|
|
}
|
|
|
|
static int searchRecursive(int x, IntList a) {
|
|
return searchRecursiveHelper(x, a, 0, a.getLength() - 1);
|
|
}
|
|
|
|
private static int searchRecursiveHelper(
|
|
int x,
|
|
IntList a,
|
|
int low,
|
|
int high
|
|
) {
|
|
if (low > high) {
|
|
return low;
|
|
}
|
|
|
|
int mid = low + (high - low) / 2;
|
|
|
|
if (a.get(mid) <= x) {
|
|
return searchRecursiveHelper(x, a, low, mid - 1);
|
|
} else {
|
|
return searchRecursiveHelper(x, a, mid + 1, high);
|
|
}
|
|
}
|
|
}
|