package com.mindprod.example;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import static java.lang.System.*;
/**
* Demonstrate binary search.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2007-05-13
* @since 2007-05-13
*/
public class TestBinSearch
{
/**
* Comparator for reverse alphabetic sorting
*/
private static final Comparator<String> order = new ReverseAlphabetically();
/**
* test binary search
*
* @param args not used
*/
public static void main( String[] args )
{
ArrayList<String> antelopes = new ArrayList<>( 10 );
antelopes.add( "kudu" );
antelopes.add( "gazelle" );
antelopes.add( "springbok" );
antelopes.add( "impala" );
antelopes.add( "duiker" );
Collections.sort( antelopes, order );
for ( String antelope : antelopes )
{
out.println( antelope );
}
int whereFound = Collections.binarySearch( antelopes, "gnu", order );
out.println( whereFound );
}
/**
* Sort in reverse alphabetical order.
* <p/>
* Defines an alternate sort order for String.
*/
private static class ReverseAlphabetically implements Comparator<String>
{
/**
* Sort in reverse alphabetical order.
* Defines an alternate sort order for String.
* Compare two String Objects.
* Compares descending .
* Informally, returns (a-b), or +ve if a is more positive than b.
*
* @param a first String to compare
* @param b second String to compare
*
* @return +ve if a>b, 0 if a==b, -ve if a<b
*/
public final int compare( String a, String b )
{
return b.compareToIgnoreCase( a );
}
}
}