CS62 - Spring 2010 - Lecture 6

  • Quiz: Write a recursive procedure to multiply two values a and b using only addition. What is the complexity of this procedure?

  • Comment on submission process

  • Today, we're talking about sorting. One of the first questions we need to ask is how are we going to compare things. For numbers, it's straightforward. What about Strings? What about other objects?
       - need to implement the Comparable interface: compareTo
          - x.compareTo(y) == 0 if x == y
             - should also have s.equals(y) be true
          - x.compareTo(y) < 0 if x < y
          - x.compareTo(y) > 0 if x > y
       - Comparable is a generic interface, i.e. you need to instantiate it with a class type "public class myClass implements Comparable<myClass>{}
          - public int compareTo(myClass obj)

  • A few quick notes on generics
       - Let's say we wanted to write a generic class that did some mathematical manipulations on the objects. We'd therefore like to restrict the type of the classes you can use to instantiate that class, in this case, to any class that inherits from java.lang.Number which has a number of methods, including intValue()
       - we can use "extends" in our generic type declaration:

       public class MoreGenerics <E extends Number> {
          public void aGenericMethod(E obj){
             int num = obj.intValue();

       - notice that we can call obj.intValue() (which is a method from java.lang.Number) because the compiler restricts the types we can use. For example
          - MoreGenerics<Integer> would be legal and compile
          - while MoreGenerics<String> would not compile
       - Similarly, for interfaces (e.g. Comparable) we use extends
          - <E extends Comparable<E>>
             - in this case, the interface is also a generic interface, so we're saying we have a generic class E that implements the interface Comparable for that same type, E

  • proofs by induction
       - prove the base case
       - prove the inductive case: show that if the case holds for i-1 then you can prove it for i
          - assume it's true for i-1
          - show that under this assumption, it's true for i
       - therefore, it must hold for n