OnJava8-Examples/arrays/ArraySearching.java

34 lines
1017 B
Java
Raw Permalink Normal View History

2015-09-07 11:44:36 -06:00
// arrays/ArraySearching.java
// (c)2021 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.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com 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) {
Rand.Pint rand = new Rand.Pint();
int[] a = new Rand.Pint().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:
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]
2016-01-25 18:05:55 -08:00
Location of 635 is 2, a[2] is 635
2015-09-07 11:44:36 -06:00
*/