// Generates a random array of positive integers. // Then finds the five largest numbers in the array. import java.util.Random; public class LargestFive { public static void printArray(int[] a) { System.out.print("\nIndex i: "); for(int i=0; i< a.length; i++) System.out.printf("%2d, ", i); System.out.print("\nElement a[i]: "); for(int i=0; i< a.length; i++) System.out.printf("%2d, ", a[i]); System.out.println("\n\n"); } public static void main(String[] args) { final boolean DEBUG=true; // We use two arrays. Original remains the same. // Copy gets overwritten during the search. int[] original = new int[10]; int[] copy = new int[10]; Random generator = new Random(); for(int i=0; i < original.length; i++) { original[i]= generator.nextInt(10)+1; copy[i] = original[i]; } if(DEBUG) printArray(original); System.out.println(); for(int k=0; k< 5; k++) { int max=-1; int idx= -1; for(int i=0; i < copy.length; i++) { if(max< copy[i]) { max=copy[i]; idx=i; } } System.out.println((k+1) + ") " + copy[idx] + " at index " + idx); copy[idx]=-1; // don't consider this number anymore //if(DEBUG) printArray(copy); } } }