Sorting in Java

Started by
2 comments, last by jfclavette 19 years, 1 month ago
I'm pretty new to Java, and have come across the following problem : I have a two dimensionnal array that I want to sort on one column (parameters: (column, asc). What's the easiest way to achieve this ? I need to get the other columns to follow and that's what's got me stumped. Are there sorting algorithms already implemented that will allow me to do this ? I'd rather not rewrite a quicksort for a variable number of column and content, and I need something rather fast. I sort Strings, numbers and Dates. The ability to plug my own comparison functions would be a plus. Note that for compatibility reasons, I have to use JDK 1.4, and hence can't use the features introduced since 1.5.
I teleported home one night; With Ron and Sid and Meg; Ron stole Meggie's heart away; And I got Sydney's leg. <> I'm blogging, emo style
Advertisement
I think you could make this easier if you encapsulate each row into an object.

You say you have Strings, numbers, and Dates. So let's make a class called DoHickey that is composed of those things.

public class DoHickey implements Comparable {  // these are your columns  public Object[] cols;  private int sortParam; // this will tell us which "column" to sort  public DoHickey(String s, int n, float f, Date d) {    cols = new Obj[4];    cols[0] = s;    cols[1] = new Integer(n); // have to create an object from the primitive type    cols[2] = new Float(f);   // which comes in handy when we are going to sort    cols[3] = d;  }  // set the parameter to sort on  // (do a check here to make sure s is a valid column number)  public void setSortParam(int s) {    sortParam = s;  }  // In order to sort DoHickey objects you need to implement Comparable  // which is just the compareTo() method  public int compareTo(Object o) {    DoHickey dh = (DoHickey) o;    return cols[sortParam].compareTo(dh.cols[sortParam]);    // this works out nice because String, Integer, Float, and Date all implement the Comparable interface  }}


Then you make a 1-D array of DoHickey objects which is an array of "rows" and sort it.

DoHickey[] dharray;// initialize it somewhereArrays.sort(dharray); // Arrays.sort will sort anything that implements Comparable


Of course, the DoHickey class does make it so you need to cast from Object when retrieving objects from the cols[] array, or you could add getter methods for each element if there aren't too many.
Read the Java docs for Comparable and Comparator.
Yeah, I didn't want to resort to encapsulating each rows in an object since there are thousands of combinations of columns for each row set, and that meant a major rework of the class hierarchy but I did it and the code is much cleaner now.

Works like a charm.

Thanks a bunch.
I teleported home one night; With Ron and Sid and Meg; Ron stole Meggie's heart away; And I got Sydney's leg. <> I'm blogging, emo style

This topic is closed to new replies.

Advertisement