Collections : Searching the specified list for the specified object using the binary search algorithm
Searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method prior to making this call.
package collection.demos;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class MyComparator implements Comparator<String>{
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
public class BinarySearchDemo {
public static void main(String[] args) {
ArrayList<String> names=new ArrayList<String>();
names.add("Joy");
names.add("Bynod");
names.add("Jaxon");
names.add("Traimer");
Collections.sort(names);
System.out.println("List : "+names);
int index=Collections.binarySearch(names,"Jaxon");
System.out.println("Element found at : "+index);
}
}
package collection.demos;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class MyComparator implements Comparator<String>{
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
public class BinarySearchDemo {
public static void main(String[] args) {
ArrayList<String> names=new ArrayList<String>();
names.add("Joy");
names.add("Bynod");
names.add("Jaxon");
names.add("Traimer");
Collections.sort(names);
System.out.println("List : "+names);
int index=Collections.binarySearch(names,"Jaxon");
System.out.println("Element found at : "+index);
}
}
Comments