// example of searching an array

public class array_mode {

    // Return mode of non-empty array $a$ of non-negative numbers.
    // For efficiency, assume the elements of $a$ are *dense*,
    // i.e. do not have huge gaps, otherwise $tally$ is *huge*:
    
       public static int mode(int[] a) {

	   // Set max to largest element of $a$:
              int max = a[0]; // max element of $a$
	      for (int i = 1; i<a.length; i++) max = Math.max(max, a[i]);
	      
	   // Count frequencies of elements in $a$:
	      int[] tally = new int[max+1]; // tally[i] == frequency of i
	      for (int k = 0; k<a.length; k++) tally[a[k]]++;

           // Search: find mode/position j of max frequency:
	      int j = 0; // mode so far
	      for (int i = 1; i<tally.length; i++) 
		  if (tally[i]>tally[j]) 
		      j = i;

           // Return mode:
	      return j;
	
    } // method mode
    
    // Test example for finding mode:
       public static void main(String[] args) {

	   int[] x = {1,2,2,3,3,3,5};  // note: 3 is the mode of $x$
	   System.out.println("Mode: " + mode(x) ); // report mode of $x$
	   
       } // method main
    
    
} // class array_mode