| Author |
Sorting elements by associated integers.
|
Michael Boehm
Ranch Hand
Joined: Jun 02, 2010
Posts: 51
|
|
I have a small number of different integers. To each integer is an associated integer. Is there a convenient way of sorting the integers in an array by their
associated integers without having to whip out something like a priority queue ? I would like to avoid creating objects and Compators if possible, mostly looking for a quick fix. Quadratic time is ok for the sorting.
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3793
|
|
I'd suggest a TreeMap. Use the numbers you want to sort by as the keys, and the other as the value. A TreeMap maintains the keys in sorted order.
Edit: assuming the "keys" are unique, of course.
|
 |
Michael Boehm
Ranch Hand
Joined: Jun 02, 2010
Posts: 51
|
|
|
Sorry, should have been more precise. The associated integer values might not all be different.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32689
|
|
Shame. The first thing I thought was, put the integer and the value into a class, and create a Comparator.
Try sorting an int[] array and sorting an Object[] array in parallel. Using a merge sort or quick sort it can run in nlogn time. You will of course have to write your own sort method which takes both arrays as parameters, and the arrays must both be the same size. If you use merge sort, those Objects associated with the same int will remain in their original order.
|
 |
Michael Boehm
Ranch Hand
Joined: Jun 02, 2010
Posts: 51
|
|
|
Ok, I decided to simply make a quick simple Point class and have it implement comparable and then use with TreeSet.
|
 |
 |
|
|
subject: Sorting elements by associated integers.
|
|
|