Advertisement
Guest User

Java Quicksort Profile

a guest
May 4th, 2014
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. class SortTest{
  2.     private static void quicksort(int[] list, int low, int high){
  3.         int pivot = list[low + (high-low)/2];
  4.         int i = low;
  5.         int j = high;
  6.         while (i <= j) {
  7.             while (list[i] < pivot) {
  8.                 i++;
  9.             }
  10.             while (list[j] > pivot) {
  11.                 j--;
  12.             }
  13.             if (i <= j) {
  14.                 int temp = list[i];
  15.                 list[i] = list[j];
  16.                 list[j] = temp;
  17.                 i++;
  18.                 j--;
  19.             }
  20.         }
  21.         if (low < j){
  22.             quicksort(list, low, j);
  23.         }
  24.         if (i < high){
  25.             quicksort(list, i, high);
  26.         }
  27.     }
  28.  
  29.     public static long testSorted(int size){
  30.         // create array
  31.         int[] sorted = new int[size];
  32.         for(int i=0; i<size; i++){
  33.             sorted[i] = i;
  34.         }
  35.         // sort it
  36.         long tstart = System.nanoTime();
  37.         quicksort(sorted, 0, size-1);
  38.         return System.nanoTime() - tstart;
  39.     }
  40.  
  41.     public static long testRandom(int size){
  42.         // create array
  43.         int[] permuted = new int[size];
  44.         for(int i=0; i<size; i++){
  45.             permuted[i] = i;
  46.         }
  47.  
  48.         // shuffle the array
  49.         for(int i=0; i<size; i++){
  50.             int swap = (int) (Math.random() * size);
  51.             int temp = permuted[swap];
  52.             permuted[swap] = permuted[i];
  53.             permuted[i] = temp;
  54.         }
  55.         // sort it
  56.         long tstart = System.nanoTime();
  57.         quicksort(permuted, 0, size-1);
  58.         return System.nanoTime() - tstart;
  59.     }
  60.  
  61.     public static void main(String[] args){
  62.         int runs = 1000; // total # of tests to average over
  63.        
  64.         for(int n=2; n<=1e6; n*=2){        
  65.             // TESTING
  66.             long tot_sorted = 0;
  67.             long tot_random = 0;
  68.             for(int i=0; i<runs; i++){
  69.                 tot_random += testRandom(n);
  70.                 tot_sorted += testSorted(n);
  71.             }
  72.             System.out.println(n+", "+tot_sorted+", "+tot_random);
  73.         }
  74.        
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement