/* * Sorts.java * * Created on August 21, 2002, 11:48 AM * * MAR 8/21/02 - I chose to do this the way Lewis and Loftus do it instead of the * way van der Linden (Just Java) does it because 1) it's simpler and (more importantly) * 2) it is simpler for the client (e.g. main). Reason 1 is not enough by itself. Using essentially * a static class - no instance variables and no non-static methods gets around OOP. * Generally OOP is good, and the cost in developer effort of doing it van der Linden's way is not * that much - declare an instance variable, a very simple constructor * BUT, the client then must know about SortingClass as an object, and must convert their * arrays to a SortingClass object before doing a sort * whereas with this approach, the client can do the sort with one statement (e.g. * Sorts.insertSort(thearrayofobjects); */ package SortSearchEtc; /** * * @author mike */ public class Sorts { /** Creates a new instance of Sorts */ public Sorts() { } /** * Does an insertion sort of any array (as long as the objects in the array * are members of a class that implements the Comparable interface) */ public static void insertSort(Comparable[] objects) { for (int index = 1; index < objects.length; index++) { Comparable key = objects[index]; int position = index; // shift larger values to the right while ((position > 0) && (objects[position - 1].compareTo(key) > 0)) { objects[position] = objects[position - 1]; position--; } objects[position] = key; } } }