Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Week3opd1;
- import java.util.Arrays;
- public class MyBinarySearchDemo<T> extends SearchDemo_v2<T> {
- public int binarySearch( Comparable<T>[ ] a, T x ) // zoek element x in 'a'
- {
- return binarySearch( a, 0, a.length-1, x );
- }
- private int binarySearch( Comparable<T>[ ] a, int low, int high,T x )
- {
- if(low>high) {
- return -1;
- }
- int mid = (low + high) / 2;
- System.out.println("Mid: "+mid);
- if (a[mid].compareTo(x) > 0) {
- return binarySearch(a,low,mid-1,x);
- } else if (a[mid].compareTo(x) < 0) {
- return binarySearch(a,mid+1,high,x);
- } else {
- return mid;
- }
- }
- public static void main(String[] args) {
- System.out.println("Seth klasse");
- MyBinarySearchDemo<Integer> sd1 = new MyBinarySearchDemo<Integer>();
- Integer[] ii = new Integer[]{45,65,34,82,30,22,10,99};
- int i = sd1.sequentialSearch(ii,30);
- System.out.println(i);
- MyBinarySearchDemo<Double> sd2 = new MyBinarySearchDemo<Double>();
- Double[] dd = new Double[]{45.0,65.0,34.0,82.0,30.0,22.0};
- i = sd2.sequentialSearch(dd,82.0);
- System.out.println(i);
- Arrays.sort(ii);
- sd1.showArray(ii);
- System.out.println(Arrays.toString(ii));
- i = sd1.binarySearch(ii,30);
- System.out.println(i);
- Arrays.sort(ii,new ReverseOrder<Integer>());
- sd1.showArray(ii);
- System.out.println(Arrays.toString(ii));
- i = sd1.binarySearch(ii,30);
- System.out.println(i);
- i = Arrays.binarySearch(ii,30, new ReverseOrder<Integer>());
- System.out.println(i);
- }
- }
Add Comment
Please, Sign In to add comment