import java.util.Random; /** Let's see how long it takes to sort an array. * Let's assume that the command line argument contains how many elements * the user wants in the array. */ public class Time2 { public static void main(String [] args) { // First, let's make sure the user is running the program correctly. if (args.length == 0) { System.out.printf("Usage: java Time2 \n"); System.exit(1); } // The number of array elements is the command-line argument. int howMany = Integer.parseInt(args[0]); Random g = new Random(); // Create an array of random numbers. It's possible some numbers // may be repeated, but it shouldn't matter for our experiment. int [] a = new int [howMany]; for (int i = 0; i < howMany; ++i) a[i] = g.nextInt(howMany); long t1 = System.currentTimeMillis(); sort(a); long t2 = System.currentTimeMillis(); System.out.printf("It took %d ms to sort %d elements.\n", t2 - t1, howMany); } /** In CS-12 you'll see much faster ways of sorting an array, * but for now, this one will do. This is the same way we sorted earlier. public static void sort(int [] a) { for (int i = 0; i < a.length; ++i) for (int j = i+1; j < a.length; ++j) if (a[i] < a[j]) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } }