Skip to content

Commit

Permalink
Merge pull request TheAlgorithms#593 from Mas281/patch-1
Browse files Browse the repository at this point in the history
Clean BinarySearch
  • Loading branch information
yanglbme authored Oct 26, 2018
2 parents 2332922 + 174b83f commit 6341199
Showing 1 changed file with 13 additions and 11 deletions.
24 changes: 13 additions & 11 deletions Searches/src/search/BinarySearch.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import java.util.Arrays;
import java.util.Random;
import java.util.stream.Stream;
import java.util.concurrent.ThreadLocalRandom
import java.util.stream.IntStream;

import static java.lang.String.format;

Expand Down Expand Up @@ -70,23 +71,24 @@ private <T extends Comparable<T>> int search(T array[], T key, int left, int rig

// Driver Program
public static void main(String[] args) {

//just generate data
Random r = new Random();
// Just generate data
Random random = ThreadLocalRandom.current();

int size = 100;
int maxElement = 100000;
Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new);


int[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray();

//the element that should be found
Integer shouldBeFound = integers[r.nextInt(size - 1)];
// 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.println(String.format("Should be found: %d. Found %d at index %d. An array length %d"
, shouldBeFound, integers[atIndex], atIndex, size));

System.out.println(format(
"Should be found: %d. Found %d at index %d. An array length %d",
shouldBeFound, integers[atIndex], atIndex, size
));

int toCheck = Arrays.binarySearch(integers, shouldBeFound);
System.out.println(format("Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex));
Expand Down

0 comments on commit 6341199

Please sign in to comment.