fork download
  1. import java.util.Random;
  2.  
  3. public class Main {
  4. private int[] theArray;
  5. private int arraySize;
  6. private int itemsInArray = 0;
  7. static long startTime;
  8. static long endTime;
  9.  
  10. public static void main(String[] args) {
  11. Main testBubbleSortAlgo = new Main(10000);
  12. testBubbleSortAlgo.generateSortedArray();
  13.  
  14. Main testBubbleSortAlgoAgain = new Main(90000);
  15. testBubbleSortAlgoAgain.generateSortedArray();
  16.  
  17. Random r = new Random();
  18. testBubbleSortAlgo.binarySearch(r.nextInt((10000 - 1) + 1) + 1);
  19. testBubbleSortAlgoAgain.binarySearch(r.nextInt((90000 - 1) + 1) + 1);
  20.  
  21. }
  22.  
  23. Main(int size) {
  24. arraySize = size;
  25. theArray = new int[size];
  26. }
  27.  
  28. public void binarySearch(int value) {
  29.  
  30. startTime = System.currentTimeMillis();
  31.  
  32. int lowIndex = 0;
  33. int highIndex = arraySize - 1;
  34.  
  35. int timesThrough = 0;
  36.  
  37. while (lowIndex <= highIndex) {
  38.  
  39. int middleIndex = (highIndex + lowIndex) / 2;
  40.  
  41. if (theArray[middleIndex] < value)
  42. lowIndex = middleIndex + 1;
  43.  
  44. else if (theArray[middleIndex] > value)
  45. highIndex = middleIndex - 1;
  46.  
  47. else {
  48.  
  49. System.out.println("\nFound a Match for " + value
  50. + " at Index " + middleIndex);
  51.  
  52. lowIndex = highIndex + 1;
  53.  
  54. }
  55.  
  56. timesThrough++;
  57.  
  58. }
  59.  
  60. endTime = System.currentTimeMillis();
  61. System.out.println("Binary Search Took " + (endTime - startTime));
  62. System.out.println("Times Through: " + timesThrough);
  63. }
  64.  
  65.  
  66. public void generateSortedArray() {
  67.  
  68. for (int i = 0; i < arraySize; i++) {
  69. theArray[i] = i;
  70. }
  71.  
  72. itemsInArray = arraySize - 1;
  73.  
  74. }
  75. }
  76.  
Success #stdin #stdout 0.03s 711168KB
stdin
Standard input is empty
stdout
Found a Match for 1475 at Index 1475
Binary Search Took 0
Times Through: 12

Found a Match for 84958 at Index 84958
Binary Search Took 0
Times Through: 15