Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorting elements by associated integers.  RSS feed

 
Michael Boehm
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, should have been more precise. The associated integer values might not all be different.
 
Campbell Ritchie
Marshal
Posts: 55751
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I decided to simply make a quick simple Point class and have it implement comparable and then use with TreeSet.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!