Du befindest dich hier: FSI Informatik » Prüfungsfragen und Altklausuren » Prüfungen im Bachelor-Studium (1. - 5. Semester) » aud » Forendiskussionen » codezuaufgabe3   (Übersicht)

import java.util.*;
 
public class Maerz16_BinSuche {
	public static void main(String[] args) {
		Tupel a=new Tupel("AuD",42);
		Tupel b=new Tupel("AuD",666);
		Tupel c=new Tupel("AuD",666);
		Tupel d=new Tupel("PFP",41);
		Tupel e=new Tupel("PFP",666);
		Tupel f=new Tupel("PFP",4711);
 
		Tupel[] test={a,b,c,d,e,f};
 
		org.junit.Assert.assertEquals(
			suche(test,new Tupel("AuD",42),new c1(),new c2()), 0 );
 
		org.junit.Assert.assertEquals(
				suche(test,new Tupel("AuD",41),new c1(),new c2()), -1 );
 
		org.junit.Assert.assertEquals(
				suche(test,new Tupel("PFP",666),new c1(),new c2()), 4 );
 
		org.junit.Assert.assertEquals(
				suche(test,new Tupel("PFP",4711),new c1(),new c2()), 5 );
	}
 
	public static <T> int suche(T[] ts, T t, Comparator<T> c1, Comparator<T> c2){
		int a=0, m, z=ts.length -1; //Anfang, Mitte, Ende
		while(z >= a){
			m= (a+z)/2;
 
			if(c1.compare(t, ts[m]) < 0){
				z=m-1;
 
			}else if(c1.compare(t, ts[m]) == 0){
 
				if(c2.compare(t, ts[m]) < 0){
					z=m-1;
 
				}else if(c2.compare(t, ts[m]) == 0){
					return m;
 
				}else{
					a=m+1;
				}
			}else {
				a=m+1;
			}
 
		}
		return -1;
	}
 
}
 
class c1 implements Comparator<Tupel>{
 
	@Override
	public int compare(Tupel o1, Tupel o2) {
		return o1.txt.compareTo(o2.txt);
	}
}
 
class c2 implements Comparator<Tupel>{
 
	@Override
	public int compare(Tupel o1, Tupel o2) {
		return o1.v.compareTo(o2.v);
	}
}
 
class Tupel{
	String txt;
	Integer v;
 
	public Tupel(String txt, Integer v) {
		this.txt = txt;
		this.v = v;
	}
 
}