CS 1723 -- Bubble Sort of doubles


Here is a low performance bubble sort. It inserts random doubles into an array and then sorts the array into order.


// SortBubble: simpel bubble sort
public class SortBubble {
   private double[] a; // holds numbers after sorting
   private int size; // size of array
   private int count; // counter for numbers as produced in order


   public SortBubble(int s) {
      size = s; count = 0;
      a = new double[size];
   }

   public void generateNumbers() {
      for (int i = 0; i < size; i++) // generate numbers to sort
         a[i] = Math.random();

   }

   public void bubbleSort() {
      for (int dummy = 0; dummy < size-1; dummy++)
         for (int i = 0; i < size-1; i++)
            if (a[i] > a[i+1]) {
               double temp = a[i];
               a[i] = a[i+1];
               a[i+1] = temp;
            }
   }

   public boolean checkSorted() { // check if in sorted order
      for (int i = 0; i < size-1; i++)
         if (a[i] >= a[i+1]) return false;
      return true;
   }
}

// SortBubbleTest: test the SortBubble class, a low performance sort public class SortBubbleTest { final static int SIZE = 50000; public static void main(String[] argv) { SortBubble bubble = new SortBubble(SIZE); System.out.println("Number of items: " + SIZE); long startTime = System.currentTimeMillis(); bubble.generateNumbers(); elapsedTime(startTime, "After generating, "); bubble.bubbleSort(); elapsedTime(startTime, "After sorting, "); System.out.println("Sorted is " + bubble.checkSorted()); } public static void elapsedTime(long startTime, String s) { long stopTime = System.currentTimeMillis(); double elapsedTime = ((double)(stopTime - startTime))/1000.0; System.out.println(s + "elapsed time: " + elapsedTime + " seconds"); } }
Here is the output of several runs, showing the times to sort different numbers of items into order:
Number of items: 1000
After generating, elapsed time: 0.016 seconds
After sorting, elapsed time: 0.125 seconds
Sorted is true  (time to sort: 0.109)

Number of items: 10000 After generating, elapsed time: 0.033 seconds After sorting, elapsed time: 8.855 seconds Sorted is true (time to sort: 8.822)
Number of items: 20000 After generating, elapsed time: 0.098 seconds After sorting, elapsed time: 36.123 seconds Sorted is true (time to sort: 36.025)
Number of items: 50000 After generating, elapsed time: 0.148 seconds After sorting, elapsed time: 253.755 seconds Sorted is true (time to sort: 253.607)
Number of items: 100000 After generating, elapsed time: 0.15 seconds After sorting, elapsed time: 1118.822 seconds Sorted is true (time to sort: 1118.672)

Revision date: 2001-11-03. (Please use ISO 8601, the International Standard.)