ShellSortTimer.java.html

  1  import java.util.Arrays;
  2  import java.util.Scanner;
  3  
  4  /**
  5     This program measures how long it takes to sort an
  6     array of a user-specified size with the Shell
  7     sort algorithm.
  8  */
  9  public class ShellSortTimer
 10  {  
 11     public static void main(String[] args)
 12     {  
 13        Scanner in = new Scanner(System.in);
 14        System.out.print("Enter array size: ");
 15        int n = in.nextInt();
 16  
 17        // Construct random array
 18     
 19        int[] a = ArrayUtil.randomIntArray(n, 100);
 20        int[] a2 = Arrays.copyOf(a, a.length);
 21        int[] a3 = Arrays.copyOf(a, a.length);
 22        
 23        // Use stopwatch to time selection sort
 24        
 25        StopWatch timer = new StopWatch();
 26        
 27        timer.start();
 28        ShellSorter.sort(a);
 29        timer.stop();
 30        
 31        System.out.println("Elapsed time with Shell sort: " 
 32              + timer.getElapsedTime() + " milliseconds");
 33  
 34        timer.reset();
 35        timer.start();
 36        Arrays.sort(a2);
 37        timer.stop();
 38  
 39        System.out.println("Elapsed time with Arrays.sort: " 
 40              + timer.getElapsedTime() + " milliseconds");
 41  
 42        if (!Arrays.equals(a, a2)) 
 43        { 
 44           throw new IllegalStateException("Incorrect sort result"); 
 45        }
 46  
 47        timer.reset();
 48        timer.start();
 49        InsertionSorter.sort(a3);
 50        timer.stop();
 51  
 52        System.out.println("Elapsed time with insertion sort: " 
 53              + timer.getElapsedTime() + " milliseconds");
 54     }
 55  }
 56  
 57