CS 241 Data Structures- Lab 4, Due 2/23 (!)

Sort Timing

Your task for this lab is to implement the three O(n^2) sorts: bubble sort, insertion sort, and selection sort; then time them on various sized lists, namely 1000, 2000, 4000, 8000, etc (by passing them to a SortTimer) to verify they are actually O(n^2).


A few random sort variations have been presented in class; use them as a model for the three sorts you must implement. Copy/paste (most of) this code into your Frame and write classes to make it code work (use NetBeans to create the Frame, then copy this piecemeal):
public class TimerFrame extends javax.swing.JFrame {

    public TimerFrame() {  // this constructor creates the form and displays it
        setSize(1000, 500);
        setTitle("SortTimer Frame");

        emit("\t\t\tT I M I N G   T H R E E   S O R T S !\n\n");
        emit("\n\nAll done!");
    /** time each of the sorts for length n
     * done by n instead of by sort so the output is easy
    private void timeStuff() {
        for (int i = 0; i < 7; i++) {
            int n = (int) Math.pow(2, i);
            time(n * 1000);  

   private void time(int n) {
        // create an array with an instance of each sort of length n 
        AbstractSort[] sorts = {new BubbleSort(n), new InsertSort(n), new SelectionSort(n)};

        emit("n=" + n);

        for (int i = 0; i < sorts.length; i++) { // for each of the sorts
            AbstractSort aSort = sorts[i];
            spewIfSmall("before", aSort, n);
            long time = SortTimer.time(aSort);
            emit(" t=" + time);
            spewIfSmall("after", aSort, n);

    void emit(String s) {
        theTA.append(s + "\t");
To produce output that looks something like:
            T I M I N G   T H R E E   S O R T S !
        	bubble	insert	 select		
	n=1000	 t=19	 t=8	 t=8	
	n=2000	 t=25	 t=1	 t=4	
	n=4000	 t=33	 t=6	 t=16	
	n=8000	 t=149	 t=28	 t=48	
	n=16000	 t=586	 t=89	 t=197	
	n=32000	 t=2513	 t=338	 t=780	
	n=64000	 t=9288	 t=1373	 t=3101	


  1. Use this (or the .zip of it on examplesFromClass) as a model (feel free to copy paste any code you like).
  2. Initialize the lists at random with numbers between 0 and n (where n is the length of the list)
  3. Test your sorts with n=8 or 10, to make sure they actually work! Come up with some way that it is quick to demonstrate that they work when you demo (i.e. a button, or menu item, or test module of whatever stripe you like).

Demo your code during lab for credit.