2018-04-06 06:54:36 +08:00
|
|
|
|
|
|
|
import java.util.Arrays;
|
|
|
|
import java.util.Random;
|
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @author Gabriele La Greca : https://github.com/thegabriele97
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
|
|
|
|
public final class IterativeBinarySearch {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* This method implements an iterative version of binary search algorithm
|
|
|
|
*
|
2018-04-09 02:05:00 +08:00
|
|
|
* @param array a sorted array
|
|
|
|
* @param key the key to search in array
|
2018-04-06 06:54:36 +08:00
|
|
|
*
|
|
|
|
* @return the index of key in the array or -1 if not found
|
|
|
|
*/
|
2018-04-09 02:05:00 +08:00
|
|
|
public static <T extends Comparable<T>> int binarySearch(T[] array, T key) {
|
2018-04-06 06:54:36 +08:00
|
|
|
int l, r, k, cmp;
|
|
|
|
|
|
|
|
l = 0;
|
|
|
|
r = array.length - 1;
|
|
|
|
|
|
|
|
while (l <= r) {
|
|
|
|
k = (l + r) / 2;
|
|
|
|
cmp = key.compareTo(array[k]);
|
|
|
|
|
|
|
|
if (cmp == 0) {
|
|
|
|
return k;
|
|
|
|
} else if (cmp < 0) {
|
|
|
|
r = --k;
|
|
|
|
} else if (cmp > 0) {
|
|
|
|
l = ++k;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
//Only a main method for test purpose
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Random rand = new Random();
|
|
|
|
int base = rand.nextInt(1000);
|
|
|
|
|
2018-04-09 02:05:00 +08:00
|
|
|
Integer[] array = new Integer[65535];
|
2018-04-06 06:54:36 +08:00
|
|
|
for (int i = 0; i < array.length; i++) {
|
|
|
|
array[i] = base + (i + 1);
|
|
|
|
}
|
|
|
|
|
2018-04-09 02:05:00 +08:00
|
|
|
//Arrays.sort(array); //if needed
|
|
|
|
Integer key = base + rand.nextInt(array.length * 2); //can generate keys that aren't in array
|
2018-04-06 06:54:36 +08:00
|
|
|
|
2018-04-09 02:05:00 +08:00
|
|
|
System.out.println(binarySearch(array, key));
|
2018-04-06 06:54:36 +08:00
|
|
|
System.out.println(Arrays.binarySearch(array, key));
|
|
|
|
}
|
2018-04-09 02:05:00 +08:00
|
|
|
}
|