Søgning vha COMPARATOR
Jeg har følgende kode:********************************************
import java.util.*;
interface COMPARATOR<T>{
int compare (T o1, T o2);
}
interface BINARYSEARCH<T> {
public <T> int search (ArrayList <? extends T> l,
T key,
COMPARATOR <? super T> c);
/* Invariant: l is a sorted list */
}
class Comparator implements COMPARATOR<String> {
public int compare (String s1, String s2) {return s1.compareTo (s2);}
}
class BinarySearch {
static public void main (String[] args) {
ArrayList<String> list = new ArrayList<String> ();
list.add ("Anton");
list.add ("Berta");
list.add ("Carsten");
}
}
*******************************************
Jeg skal lave search metoden, men har ikke det store kendskab til java syntax.
Mit foreløbige forsøg ser ud som følgende:
*******************************************
import java.util.*;
interface COMPARATOR<T>{
int compare (T o1, T o2);
}
interface BINARYSEARCH<T> {
public <T> int search (ArrayList <? extends T> l,
T key,
COMPARATOR <? super T> c);
/* Invariant: l is a sorted list */
}
class Comparator implements COMPARATOR<String> {
public int compare (String s1, String s2) {return s1.compareTo (s2);}
}
class BinarySearch{
static public void main (String[] args)
{
ArrayList<String> list = new ArrayList<String> ();
list.add ("Anton");
list.add ("Berta");
list.add ("Carsten");
list.add ("Dennis");
list.add ("Elisabeth");
list.add ("Frank");
list.add ("Grooom");
search(list, "Carsten", Some_ref_to_a_comparator);
}
public int search (ArrayList l, String key, Comparator c) // 'key' must be equal to an element in 'l'
{
int left = 0;
int right = l.size()-1;
int currentLookAt;
do
{
currentLookAt = ((left+right)/2);
if (c.compare(key, (String)l.get(currentLookAt))<0)
{
right = currentLookAt;
}
else //Search string is "larger" than the current index
{
left = currentLookAt;
}
}while (c.compare(key, (String)l.get(currentLookAt)) != 0);
return currentLookAt;
}
}
******************************************************
Jeg er i tvivl om jeg overhovedet er startet korrekt, så lidt feedback ville være rart.
Det virker underligt at skulle sende Comparator med som argument.