Skip to main content
ICT
Lesson A17 - Quadratic Sorting Algorithms
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

G. Sorting Objects page 9 of 11

  1. Notice that the sorts we developed above know how to compare Integers. Comparison is built into the Integer class. What if we wanted to write a sort that could work on Strings? You cannot use ‘<’ on Strings. Remember you have to use the compareTo method.

  2. To convert the BubbleSort, make the following changes that are highlighted in yellow.

    void bubbleSort(ArrayList <String> list){
      for (int outer = 0; outer < list.length - 1; outer++){
        for (int inner = 0; inner < list.size()-outer-1; inner++){
          if (list.get(inner).compareTo(list.get(inner + 1) > 0){
              //swap list[inner] & list[inner+1]
              String temp = list.get(inner);
              list.set(inner, list.get(inner + 1));
              list.set(inner + 1, temp);
          }
        }
      }
    }

  3. If I am able to sort my data, there must be an order defined for it. Classes that have an order should have a compareTo method. Java defines an Interface, Comparable, just for this purpose (see below for some information on Comparable). To make a BubbleSort that will work on any objects that implement Comparable, make the following changes, again highlighted in yellow.

    void bubbleSort(ArrayList <Comparable> list){
      for (int outer = 0; outer < list.length - 1; outer++){
        for (int inner = 0; inner < list.size()-outer-1; inner++){
          if (list.get(inner).compareTo(list.get(inner + 1) > 0){
              //swap list[inner] & list[inner+1]
              Comparable temp = list.get(inner);
              list.set(inner, list.get(inner + 1));
              list.set(inner + 1, temp);
          }
        }
      }
    }

    Now this method is quite reusable because we can use it to sort any Comparable object. The compareTo interface follows.

    Interface java.lang.Comparable
    int compareTo(Object other)
        // returns value < 0 if this is less than other
        // returns value = 0 if this is equal to other
        // returns value > 0 if this is greater than other

    Remember to consider whether or not it makes sense to compare objects that you build. If it does, implement the Comparable Interface. It would also make sense to provide an equals method for your class.

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.