/*
 * [TestBinSearch.java]
 *
 * Summary: Demonstrate binary search.
 *
 * Copyright: (c) 2007-2017 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2007-05-13
 */
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 )
        {
        // create a Collection of antelope species
        ArrayList<String> antelopes = new ArrayList<>( 10 );
        antelopes.add( "kudu" );
        antelopes.add( "gazelle" );
        antelopes.add( "springbok" );
        antelopes.add( "impala" );
        antelopes.add( "duiker" );
        // sort in reverse order
        Collections.sort( antelopes, order );
        // display Collection
        // springbok
        // kudu
        // impala
        // gazelle
        // duiker
        for ( String antelope : antelopes )
            {
            out.println( antelope );
            }
        // Binary search
        // negative wherefound means where to insert, positive means where found.
        int whereFound = Collections.binarySearch( antelopes, "gnu", order );
        out.println( whereFound );
        // Result is -4. Thus the insert point is +3.
        // "gnu" would be sitting at index 3 after insertion,
        // between impala and gazelle.
        // gazelle and duiker would slide up.
        // gnu would sit where gazelle used to.
        }

    /**
     * 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&gt;b, 0 if a==b, -ve if a&lt;b
         */
        public final int compare( String a, String b )
            {
            return b.compareToIgnoreCase( a );
            }
        }
    }