Add tests, remove main in BinarySearch (#5663)

This commit is contained in:
Hardik Pawar
2024-10-11 00:52:42 +05:30
committed by GitHub
parent ac2c88ca9f
commit ca5fbbf0a9
3 changed files with 109 additions and 26 deletions

View File

@ -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);
}
}