Guest User

Untitled

a guest
Feb 20th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. package Week3opd1;
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class MyBinarySearchDemo<T> extends SearchDemo_v2<T> {
  6.    
  7.     public int binarySearch( Comparable<T>[ ] a, T x ) // zoek element x in 'a'
  8.     {
  9.         return binarySearch( a, 0, a.length-1, x );
  10.     }
  11.    
  12.     private int binarySearch( Comparable<T>[ ] a, int low, int high,T x )
  13.     {
  14.         if(low>high) {
  15.             return -1;
  16.         }
  17.         int mid = (low + high) / 2;
  18.         System.out.println("Mid: "+mid);
  19.         if (a[mid].compareTo(x) > 0) {
  20.             return binarySearch(a,low,mid-1,x);
  21.         } else if (a[mid].compareTo(x) < 0) {
  22.             return binarySearch(a,mid+1,high,x);
  23.         } else {
  24.             return mid;
  25.         }
  26.     }
  27.    
  28.     public static void main(String[] args) {
  29.         System.out.println("Seth klasse");
  30.         MyBinarySearchDemo<Integer> sd1 = new MyBinarySearchDemo<Integer>();
  31.        
  32.         Integer[] ii = new Integer[]{45,65,34,82,30,22,10,99};
  33.         int i = sd1.sequentialSearch(ii,30);
  34.         System.out.println(i);
  35.  
  36.         MyBinarySearchDemo<Double> sd2 = new MyBinarySearchDemo<Double>();
  37.         Double[] dd = new Double[]{45.0,65.0,34.0,82.0,30.0,22.0};
  38.         i = sd2.sequentialSearch(dd,82.0);
  39.         System.out.println(i);
  40.        
  41.         Arrays.sort(ii);
  42.         sd1.showArray(ii);
  43.         System.out.println(Arrays.toString(ii));
  44.         i = sd1.binarySearch(ii,30);
  45.         System.out.println(i);
  46.        
  47.         Arrays.sort(ii,new ReverseOrder<Integer>());
  48.         sd1.showArray(ii);
  49.         System.out.println(Arrays.toString(ii));
  50.         i = sd1.binarySearch(ii,30);
  51.         System.out.println(i);
  52.         i = Arrays.binarySearch(ii,30, new ReverseOrder<Integer>());
  53.         System.out.println(i);
  54.     }
  55.    
  56. }
Add Comment
Please, Sign In to add comment