OnJava8-Examples/arrays/ArraySearching.java

34 lines
1.0 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// arrays/ArraySearching.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// Using Arrays.binarySearch()
2015-06-15 17:47:35 -07:00
import java.util.*;
import onjava.*;
2016-01-25 18:05:55 -08:00
import static onjava.ArrayShow.*;
2015-06-15 17:47:35 -07:00
public class ArraySearching {
public static void main(String[] args) {
2016-01-25 18:05:55 -08:00
Rand.int_ rand = new Rand.int_();
int[] a = new Rand.int_().array(25);
2015-06-15 17:47:35 -07:00
Arrays.sort(a);
2016-01-25 18:05:55 -08:00
show("Sorted array", a);
2015-06-15 17:47:35 -07:00
while(true) {
2016-01-25 18:05:55 -08:00
int r = rand.getAsInt();
2015-06-15 17:47:35 -07:00
int location = Arrays.binarySearch(a, r);
if(location >= 0) {
2015-12-02 09:20:27 -08:00
System.out.println(
"Location of " + r + " is " + location +
2016-01-25 18:05:55 -08:00
", a[" + location + "] is " + a[location]);
2015-06-15 17:47:35 -07:00
break; // Out of while loop
}
}
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2016-01-25 18:05:55 -08:00
Sorted array: [125, 267, 635, 650, 1131, 1506, 1634,
2400, 2766, 3063, 3768, 3941, 4720, 4762, 4948, 5070,
5682, 5807, 6177, 6193, 6656, 7021, 8479, 8737, 9954]
Location of 635 is 2, a[2] is 635
2015-09-07 11:44:36 -06:00
*/