Skip to main content
ICT
Lesson A17 - Quadratic Sorting Algorithms
 
Main   Previous Next
 

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.