Presentation is loading. Please wait.

Presentation is loading. Please wait.

Binary Search class binarysearch {

Similar presentations


Presentation on theme: "Binary Search class binarysearch {"— Presentation transcript:

1 Binary Search class binarysearch {
public static void main (String arg[]) { int x, i; x = 250; int m [] = {2, 25, 34, 45, 52, 99, 106, 250, 1000}; i=bsearch (x,m,0, 8); if (i >=0) {System.out.println ("item found at position=" + (i+1));} else System.out.println ("item not found"); }

2 Binary Search public static int bsearch (int item, int larray [], int m, int n) { int i = -1; if (m == n) {if (item == larray[m]) return m; else return i;}; i = (m+n)/2; if (larray[i]==item) return i; if (larray[i]<item) {i= (bsearch(item,larray, i+1, n));} else if (larray[i]>item) i= (bsearch(item, larray, m, i-1)); return i; } } // end class

3 Search import java.util.*; public class Search {
static int a[],counter; /* returns index of the first * occurrence of target in a[] * or -1 if not present */ static int simpleSearch(int target) { counter=0; for(int i=0;i<a.length;i++) { counter++; if(a[i]==target) return i; } return -1;

4 Search /* assumes a[] is sorted in * ascending order */
static int binarySearch(int target) { int rt=a.length-1, lt=0, m=-1; counter=0; while (lt<=rt){ m=(lt+rt)/2; counter++; if(target<a[m]) rt=m-1; else if (target>a[m]) lt=m+1; else return m; } return -1;

5 Search import java.util.*; static void genFixedRandomArray(int size) {
Random r=new Random(0); a=new int[size]; for(int i=0;i<size;i++) a[i]=r.nextInt(1000); } static void sort() { Arrays.sort(a); static void printArray(){ System.out.print("[ "); for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println("]"); static void printCounter(){ System.out.println("No. of ops="+counter); }//end class


Download ppt "Binary Search class binarysearch {"

Similar presentations


Ads by Google