50 lines
1.2 KiB
Java
50 lines
1.2 KiB
Java
package search;
|
|
|
|
/**
|
|
* @author Nikita Doschennikov (me@fymio.us)
|
|
*/
|
|
public class BinarySearch3233 {
|
|
|
|
public static void main(String[] args) {
|
|
IntList a = new IntList();
|
|
for (String arg : args) {
|
|
a.put(Integer.parseInt(arg));
|
|
}
|
|
|
|
// System.out.println(searchIterative(a));
|
|
System.out.println(searchRecursive(a, 0, a.getLength() - 1));
|
|
}
|
|
|
|
static int searchIterative(IntList a) {
|
|
int arrLength = a.getLength();
|
|
if (arrLength <= 1) return 0;
|
|
|
|
int low = 0, high = arrLength - 1;
|
|
|
|
while (low < high) {
|
|
int mid = low + (high - low) / 2;
|
|
if (a.get(mid) < a.get(arrLength - 1)) {
|
|
high = mid;
|
|
} else {
|
|
low = mid + 1;
|
|
}
|
|
}
|
|
|
|
return low;
|
|
}
|
|
|
|
static int searchRecursive(IntList a, int low, int high) {
|
|
if (low >= high) {
|
|
return low;
|
|
}
|
|
|
|
int mid = low + (high - low) / 2;
|
|
if (a.get(mid) < a.get(a.getLength() - 1)) {
|
|
return searchRecursive(a, low, mid);
|
|
} else {
|
|
return searchRecursive(a, mid + 1, high);
|
|
}
|
|
}
|
|
|
|
|
|
} |