• 0

need to sort something in java


Question

ok here's my situation, i have most of this project done i just need to sort this one array i have. it's a two dimensional string area, with a contributor's key in [count][0] and the position of the contributors record in [count][1]

how can i sort this array based on the key and keeping the position together with the key....????

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

http://en.wikipedia.org/wiki/Sorting_algorithm

For example, u could use something like that: http://en.wikipedia.org/wiki/Quicksort#Java

by simply changing all reference to array[x] to array[x][0] and by adding 3 lines in the swap method to also swap array[x][1] at the same time u swap array[x][0]...

Also, the Comparator is not really useful; u can just remove all reference to it, and do a simple comparaison instead. See the Javadoc of Comparator to be able to translate if (cmp.compare(array, pivot) <= 0) into a simple comparaison...

Link to comment
Share on other sites

  • 0

ok i fixed the swap method to include the position to get swapped....

i'm trying to do this all in the class i already have as another method but i might have to just use that class structure to do it...what do you think?

Link to comment
Share on other sites

  • 0

Since ur customizing the code to work only in your particular case, I'd say you should put the methods in the class you already have.

Class isolation would be better if the quicksort algorithm was generic.

Link to comment
Share on other sites

  • 0

You can use Comparator like this:

String[][] data = new String[5][2];
data[0][0] = "Charlie";
data[0][1] = "14";

data[1][0] = "Bravo";
data[1][1] = "1";

data[2][0] = "Delta";
data[2][1] = "59";

data[3][0] = "Alpha";
data[3][1] = "25";

data[4][0] = "Echo";
data[4][1] = "54";

Arrays.sort(data, new Comparator() {
  public int compare(Object o1, Object o2) {
    String[] d1 = (String[])o1;
    String[] d2 = (String[])o2;
    return d1[0].compareTo(d2[0]);
  }

  public boolean equals(Object obj) {return false;}
});

Link to comment
Share on other sites

  • 0

well i modified the quicksort class that Mouton showed me and that works good, now i'm just working on some other parts, like retrieving data from oos....thx

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.