/**

 * This class is revised from the RandomNumbers.java from the Weiss book, "Data Structures & Problem Solving Using Java" (4th edition).

 * It demonstrate how to use the sort() and binarySearch() methods with Integer Arrays.

**/

 

import java.util.Random;

import java.util.Arrays;

import java.util.Collections;

 

public class RandomNumbers2

{

    // Generate random numbers (from 1 to DIFF_NUMBERS)

    // Print number of occurrences of each number

 

    public static final int DIFF_NUMBERS     =   10;

    public static final int TOTAL_NUMBERS    = 10000;

 

    private static void display (Integer [] ar) {

        System.out.println( Arrays.toString(ar) );

    }

 

    public static void main( String [ ] args )

    {

        // Create the array of Integer; initialize to zero

        Integer [ ] numbers = new Integer[ DIFF_NUMBERS + 1 ];

        for( int i = 0; i < numbers.length; i++ )

            numbers[ i ] = 0;

 

        Random r = new Random( );

       

        // Generate the numbers

        for( int i = 0; i < TOTAL_NUMBERS; i++ )

            numbers[ r.nextInt( DIFF_NUMBERS ) + 1 ]++;

         display (numbers);

 

         Arrays.sort(numbers); // sorting the numbers in the array into ascending order

         System.out.println ("After sorting ...");

         display (numbers);

 

         int position = Arrays.binarySearch(numbers, TOTAL_NUMBERS / DIFF_NUMBERS); // search the array using binary search

         if ( position < 0 )

             System.out.println(TOTAL_NUMBERS / DIFF_NUMBERS + " is not found in the array.");

         else

             System.out.println (TOTAL_NUMBERS / DIFF_NUMBERS + " is at position " + position);

 

         Arrays.sort(numbers, Collections.reverseOrder()); // sorting the numbers in the array into descending order

             //reverseOrder() is a method defined in the Collections class

 

         // Collections.reverse(Arrays.asList(numbers)); //somehow this does not work!?

 

         System.out.println("\nAfter reverse sorting -----------");

         display (numbers);

 

         position = Arrays.binarySearch(numbers, TOTAL_NUMBERS / DIFF_NUMBERS); // search the array using binary search

         if ( position < 0 )

             System.out.println(TOTAL_NUMBERS / DIFF_NUMBERS + " is not found in the array.");

         else

             System.out.println (TOTAL_NUMBERS / DIFF_NUMBERS + " is at position " + position);

 

    } // main

}