2015-09-07 11:44:36 -06:00
|
|
|
// arrays/ArraySearching.java
|
2015-06-15 17:47:35 -07:00
|
|
|
// Using Arrays.binarySearch().
|
|
|
|
import java.util.*;
|
2015-11-03 12:00:44 -08:00
|
|
|
import java.util.function.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
import com.mindviewinc.util.*;
|
|
|
|
|
|
|
|
public class ArraySearching {
|
|
|
|
public static void main(String[] args) {
|
2015-11-03 12:00:44 -08:00
|
|
|
Supplier<Integer> gen =
|
|
|
|
new RandomSupplier.Integer(1000);
|
2015-06-15 17:47:35 -07:00
|
|
|
int[] a = ConvertTo.primitive(
|
|
|
|
Generated.array(new Integer[25], gen));
|
|
|
|
Arrays.sort(a);
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("Sorted array: " + Arrays.toString(a));
|
2015-06-15 17:47:35 -07:00
|
|
|
while(true) {
|
2015-11-03 12:00:44 -08:00
|
|
|
int r = gen.get();
|
2015-06-15 17:47:35 -07:00
|
|
|
int location = Arrays.binarySearch(a, r);
|
|
|
|
if(location >= 0) {
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("Location of " + r + " is " + location +
|
2015-06-15 17:47:35 -07:00
|
|
|
", a[" + location + "] = " + a[location]);
|
|
|
|
break; // Out of while loop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
Sorted array: [128, 140, 200, 207, 258, 258, 278, 288, 322,
|
|
|
|
429, 511, 520, 522, 551, 555, 589, 693, 704, 809, 861, 861,
|
|
|
|
868, 916, 961, 998]
|
|
|
|
Location of 322 is 8, a[8] = 322
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|