Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class SortTest{
- private static void quicksort(int[] list, int low, int high){
- int pivot = list[low + (high-low)/2];
- int i = low;
- int j = high;
- while (i <= j) {
- while (list[i] < pivot) {
- i++;
- }
- while (list[j] > pivot) {
- j--;
- }
- if (i <= j) {
- int temp = list[i];
- list[i] = list[j];
- list[j] = temp;
- i++;
- j--;
- }
- }
- if (low < j){
- quicksort(list, low, j);
- }
- if (i < high){
- quicksort(list, i, high);
- }
- }
- public static long testSorted(int size){
- // create array
- int[] sorted = new int[size];
- for(int i=0; i<size; i++){
- sorted[i] = i;
- }
- // sort it
- long tstart = System.nanoTime();
- quicksort(sorted, 0, size-1);
- return System.nanoTime() - tstart;
- }
- public static long testRandom(int size){
- // create array
- int[] permuted = new int[size];
- for(int i=0; i<size; i++){
- permuted[i] = i;
- }
- // shuffle the array
- for(int i=0; i<size; i++){
- int swap = (int) (Math.random() * size);
- int temp = permuted[swap];
- permuted[swap] = permuted[i];
- permuted[i] = temp;
- }
- // sort it
- long tstart = System.nanoTime();
- quicksort(permuted, 0, size-1);
- return System.nanoTime() - tstart;
- }
- public static void main(String[] args){
- int runs = 1000; // total # of tests to average over
- for(int n=2; n<=1e6; n*=2){
- // TESTING
- long tot_sorted = 0;
- long tot_random = 0;
- for(int i=0; i<runs; i++){
- tot_random += testRandom(n);
- tot_sorted += testSorted(n);
- }
- System.out.println(n+", "+tot_sorted+", "+tot_random);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement