mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-12-19 07:00:35 +08:00
@@ -41,12 +41,7 @@ class BinarySearch implements SearchAlgorithm {
|
||||
* @param right The upper bound
|
||||
* @return the location of the key
|
||||
*/
|
||||
private <T extends Comparable<T>> int search(
|
||||
T[] array,
|
||||
T key,
|
||||
int left,
|
||||
int right
|
||||
) {
|
||||
private <T extends Comparable<T>> int search(T[] array, T key, int left, int right) {
|
||||
if (right < left) {
|
||||
return -1; // this means that the key not found
|
||||
}
|
||||
@@ -71,12 +66,11 @@ class BinarySearch implements SearchAlgorithm {
|
||||
int size = 100;
|
||||
int maxElement = 100000;
|
||||
|
||||
Integer[] integers = IntStream
|
||||
.generate(() -> r.nextInt(maxElement))
|
||||
.limit(size)
|
||||
.sorted()
|
||||
.boxed()
|
||||
.toArray(Integer[]::new);
|
||||
Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement))
|
||||
.limit(size)
|
||||
.sorted()
|
||||
.boxed()
|
||||
.toArray(Integer[] ::new);
|
||||
|
||||
// The element that should be found
|
||||
int shouldBeFound = integers[r.nextInt(size - 1)];
|
||||
@@ -84,15 +78,11 @@ class BinarySearch implements SearchAlgorithm {
|
||||
BinarySearch search = new BinarySearch();
|
||||
int atIndex = search.find(integers, shouldBeFound);
|
||||
|
||||
System.out.printf(
|
||||
"Should be found: %d. Found %d at index %d. An array length %d%n",
|
||||
shouldBeFound,
|
||||
integers[atIndex],
|
||||
atIndex,
|
||||
size
|
||||
);
|
||||
System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n",
|
||||
shouldBeFound, integers[atIndex], atIndex, size);
|
||||
|
||||
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
|
||||
System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
|
||||
System.out.printf(
|
||||
"Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user