Practice: Reading Code

Problem 1

01   public void 3Sorts(E[] data, Comparator<E> c) {
02     for (int i = 0; i <= data.length; i++) {
03       for (int j = i; j < data.length; j++) 
04         int temp = data[j];
05         if (data[j] > data[j + 1]) {
06           swap(data[j], data[j + 1];
07         }
08       }
09     }
10   }
11
12
13   private E getMinimum(E[] data, Comparator<E> c)
14     int min = data[0];
15     for (int i = 0; i < data.length; i += 2) {
16       if (c.compare(min, data[i]) < 0) {
17         min = data[i];
18       }
19     }
20     return min;
21   }

Problem 2

Fix the bubble sort so that it has BigO(n) when it runs on a sorted array.

public void bubbleSort(E[] data, Comparator<E> c) {          
  for (int i = 0; i < data.length; i++) {         
    for (int j = 0; j < data.length - i; j++) {   
      if (c.compare(data[j], data[j + 1]) > 0) {  
        swap(data[j], data[j + 1]);               
      }                                           
    }                                             
  }                                               
}                                                 

Show me your code before you leave