Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class TestBubbleSort2 {
- /**
- * Program: TestBubbleSort2.java
- * Purpose: Test running time of bubble sort with sorted versus unsorted arrays.
- * Creator: Chris Clarke
- * Created: 05.02.2015
- */
- static final int MAX=100000; // a hundred thousand
- public static int[] initSortedArray() {
- int[] theArray = new int[MAX];
- for (int i=0; i<theArray.length; i++) {
- theArray[i] = i;
- } // for
- return theArray;
- } // initSortedArray()
- public static int[] getShuffledArray(int min, int max) {
- /**
- * max is the array size
- * when min=0, range is 0 to max-1
- * shuffle or rearrange the array values
- */
- int[] theArray, results;
- theArray = new int[max];
- results = new int[max];
- int r; // a random number
- // initialise the array
- for (int i=0; i<max; i++)
- theArray[i]=i+min; // when min=1, range is 1 to max inclusive
- // when min=0, range is 0 to max-1 inclusive
- // pick n numbers
- for (int i=0; i<max; i++) {
- // range 1 to 49, 1 to 48 etc
- r = (int) ((max-i) * Math.random());
- // store results
- results[i] = theArray[r];
- // move last number in theArray to position r
- theArray[r] = theArray[max-1-i];
- } // end for
- return results;
- } // end getShuffledArray()
- public static int[] sort(int[] a) {
- // apply bubblesort algorithm to array a
- int i, j, temp;
- int len = a.length;
- boolean swaps; // optimise code: when no swaps, array is sorted
- for (i=0; i<len-1; i++) {
- swaps = false;
- for (j=0; j<len-1-i; j++) {
- if (a[j]>a[j+1]) {
- // swap
- temp=a[j];
- a[j]=a[j+1];
- a[j+1]=temp;
- swaps = true;
- } // if
- } // for j
- if (!swaps) break; // from outer loop
- } // for i
- return a;
- } // sort()
- public static void main(String[] args) {
- NanoTimer timer = new NanoTimer();
- int[] sorted = initSortedArray();
- int[] unsorted = getShuffledArray(0, MAX);
- System.out.println("Array size: "+sorted.length);
- System.out.println("Sorting sorted array...");
- timer.setStartTime();
- sorted = sort(sorted);
- timer.setStopTime();
- System.out.println("Sorted. Running time: "+timer.toString());
- System.out.println("Sorting unsorted array...");
- timer.setStartTime();
- sorted = sort(unsorted);
- timer.setStopTime();
- System.out.println("Sorted. Running time: "+timer.toString());
- } // main()
- } // class TestBubbleSort2
- class NanoTimer {
- /**
- * Class: NanoTimer.java
- * Purpose: Get program running times in nanoseconds
- * Creator: Chris Clarke
- * Created: 03.04.2014
- */
- private long startTime = 0, runningTime = -1;
- public void setStartTime() {
- startTime = System.nanoTime();
- }
- public void setStopTime() {
- runningTime = System.nanoTime() - startTime;
- }
- public String toString() {
- if (runningTime == -1)
- return "Error in running time.";
- return runningTime+" nanoseconds";
- }
- } // class NanoTimer
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement