aspose file tools
The moose likes Beginning Java and the fly likes Sorting elements by associated integers. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Sorting elements by associated integers." Watch "Sorting elements by associated integers." New topic
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
    
    1

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
    
    4
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.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Sorting elements by associated integers.
 
Similar Threads
Sorting using Mapreduce
Wrappers and primitives comparison:
sorting array
Sorting types - which is faster?
Question on Practice Exams Book from K&B