Binary searching versus Sequential

/** * Finds the specific prime number in a given array * @Charlie Barton * @version 1.24 */ public class BinaryVSSequ { int counter = 0; int counter2 = 0; public BinaryVSSequ() { int count = 0; int[] nums = new int[50]; int test = 0; int random2 = 0; boolean isAPrime=false; boolean prime = false; while(count<50){ int random = (int)(Math.random() * 200 + 1); if(isAPrime(random) == true){ nums[count] = random; count++; } } for(int i = 0; i<nums.length; i++){ //System.out.print(" " + nums[i]); } insertionSort(nums); count = 0; while(count<1){ random2 = (int)(Math.random() * 200 + 1); if(isAPrime(random2) == true){ test = random2; count++; } } // System.out.println(test); int ss = sequentialSearch(test, nums); int bs = binarySearch(test, nums); if(bs > -1){ System.out.println("BS Number does exist! " + test) ; System.out.println("It took " + counter2 + " tries"); }else{ System.out.println("Number does not exist"); } if(ss > -1){ System.out.println("SS Number does exist!: " + test); System.out.println("It took " + counter + " tries"); }else{ System.out.println("Number does not exist"); } for(int i = 0; i<nums.length; i++){ //System.out.print(" " + nums[i]); } } public void insertionSort(int[] a) { for(int i=1; i<a.length; i++){ int key = a[i]; int j = i-1; while(j>=0 && a[j]>key){ // a[i] = a[j]; a[j+1] = a[j]; a[j] = key; j--; } } } public int sequentialSearch(int test, int[] nums){ for(int i = 0; i <nums.length; i++){ if(test == nums[i]){ return 10; } counter++; } return -1; } public int binarySearch(int test, int[] nums){ int high = nums.length; int low = 0; while(low<=high){ int middle = (low+high) /2; if (test> nums[middle] ){ low = middle +1; counter2++; } else if (test< nums[middle]){ high = middle -1; counter2++; } else { // The element has been found return middle; } } return -1; } public boolean isAPrime(int y) { boolean isAPrime=true; int num=2; while(num<y){//can do y/2 if(y%num==0) return false; num++; } return isAPrime; } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.