mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 09:06:51 +08:00
Add tests, remove main
in BinarySearch
(#5663)
This commit is contained in:
@ -1,10 +1,6 @@
|
||||
package com.thealgorithms.searches;
|
||||
|
||||
import com.thealgorithms.devutils.searches.SearchAlgorithm;
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
/**
|
||||
* Binary search is one of the most popular algorithms The algorithm finds the
|
||||
@ -57,26 +53,4 @@ class BinarySearch implements SearchAlgorithm {
|
||||
return search(array, key, median + 1, right);
|
||||
}
|
||||
}
|
||||
|
||||
// Driver Program
|
||||
public static void main(String[] args) {
|
||||
// Just generate data
|
||||
Random r = ThreadLocalRandom.current();
|
||||
|
||||
int size = 100;
|
||||
int maxElement = 100000;
|
||||
|
||||
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)];
|
||||
|
||||
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);
|
||||
|
||||
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
|
||||
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