Leave a Reply 3

Your email address will not be published. Required fields are marked *


duff

duff

D. tested with code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class SortAndSearch2 {

static final Comparator IntegerComparator = new Comparator() {
public int compare(Integer n1, Integer n2) {
return n2.compareTo(n1);
}
};

public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(4);
list.add(1);
list.add(3);
list.add(2);
Collections.sort(list, null);
System.out.println(Collections.binarySearch(list, 3));
Collections.sort(list, IntegerComparator);
System.out.println(Collections.binarySearch(list, 3));

}
}

Pavel

Pavel

I agree for D (2 1)

Improved code for testing below:

public class SortAndSearch2 {

static final Comparator IntegerComparator = new Comparator() {
@Override
public int compare(Integer n1, Integer n2) {
return n2.compareTo(n1);
}
};

public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(4);
list.add(1);
list.add(3);
list.add(2);
System.out.println(list);
Collections.sort(list, null);
System.out.println(list);
System.out.println(Collections.binarySearch(list, 3));
Collections.sort(list, IntegerComparator);
System.out.println(list);
System.out.println(Collections.binarySearch(list, 3));

}
}

leo yu

leo yu

I don’t think there is correct answer in the answer list.
As the java doc,
public static int binarySearch(List list, T key, Comparator c)
Searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the specified comparator (as by the sort(List, Comparator) method), prior to making this call. ****If it is not sorted, the results are undefined. If the list contains multiple elements equal to the specified object, there is no guarantee which one will be found.****
I tested, the 2nd binarySearch result is undefined since the IntegerComparator sort the list in ascending order.

attached my example
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;

public class SortAndSearch{
static final Comparator intComparator = new Comparator(){
public int compare(Integer i1, Integer i2){
return i2.compareTo(i1);
}
};

public static void main(String[] args){
List li = new ArrayList();
li = Arrays.asList(new Integer[]{4,6,2,1});

Collections.sort(li);
System.out.println(Collections.binarySearch(li,2));

Collections.sort(li, intComparator);
System.out.println(Collections.binarySearch(li,2));

}

}