import java.util.Random;
public class Main {
private int[] theArray;
private int arraySize;
private int itemsInArray = 0;
static long startTime;
static long endTime;
public static void main
(String[] args
) { Main testBubbleSortAlgo = new Main(10000);
testBubbleSortAlgo.generateSortedArray();
Main testBubbleSortAlgoAgain = new Main(90000);
testBubbleSortAlgoAgain.generateSortedArray();
testBubbleSortAlgo.binarySearch(r.nextInt((10000 - 1) + 1) + 1);
testBubbleSortAlgoAgain.binarySearch(r.nextInt((90000 - 1) + 1) + 1);
}
Main(int size) {
arraySize = size;
theArray = new int[size];
}
public void binarySearch(int value) {
startTime
= System.
currentTimeMillis();
int lowIndex = 0;
int highIndex = arraySize - 1;
int timesThrough = 0;
while (lowIndex <= highIndex) {
int middleIndex = (highIndex + lowIndex) / 2;
if (theArray[middleIndex] < value)
lowIndex = middleIndex + 1;
else if (theArray[middleIndex] > value)
highIndex = middleIndex - 1;
else {
System.
out.
println("\nFound a Match for " + value
+ " at Index " + middleIndex);
lowIndex = highIndex + 1;
}
timesThrough++;
}
endTime
= System.
currentTimeMillis(); System.
out.
println("Binary Search Took " + (endTime
- startTime
)); System.
out.
println("Times Through: " + timesThrough
); }
public void generateSortedArray() {
for (int i = 0; i < arraySize; i++) {
theArray[i] = i;
}
itemsInArray = arraySize - 1;
}
}