Sequential and Binary Search

public class sequentialSearch { int ssCount = 0; int bCount = 0; public sequentialSearch() { int count = 0; int[] nums = new int[10]; while(count<10){ 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]); } int random = (int)(Math.random() * 200 + 1); int ss = sequentialSearch(random, nums); if(ss>-1) System.out.println(nums[ss] ); else System.out.println("Number does not exist" ); insertionSort(nums); System.out.println(" " ); int bs = binarySearch(random,nums); for(int i = 0; i<nums.length; i++){ System.out.print(" " + nums[i]); } } public int binarySearch(int r,int[] nums){ int high = nums.length; int low = 0; int middle = (high - low)/2; while(middle>1){ if(r>middle){ low= middle + 1; middle = ((high - middle)/2) + low; }else if(r<nums [middle]){ high = middle -1; middle = (high - low)/2; }else{ return middle; } } return -1; } public int sequentialSearch(int r, int[] nums){ for (int i = 0; i<nums.length; i++){ ssCount++; if(r==nums[i]) return i; } return -1; } 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 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.