• Post Reply Bookmark Topic Watch Topic
  • New Topic

Heap Sorting  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible to get the heap sort to sort an array of objects rather than simply an array of numbers? I'm working on a demo program I call "Little Black Book," wherein I have the names of several people and their ages. Each person is an instance of the object Friend and each object stores a seperate name and age. Could I implement a heap sort to directly sort through all instances of Friend and place them in an array ordered from youngest to oldest? Would this require something besides a basic heap sort? Any help would be greatly appreciated. Thanks!
 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I guess you can place the objects in a collection and use a comparator:



Or use a sorted set or just Collections.sort() while implementing the Comparable interface in the Friend class.
[ March 31, 2006: Message edited by: Manuel Palacio ]
 
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could implement such a heap sort. However, there is no need to do so, unless for practice or for homework. Java provides a variety of ways of sorting.

First, your Friend class needs to implement compareTo(), equals() and probably hashCode(). Your implementations of these should compare the ages first, as that's the main thing on which you want to sort. If the ages are equal, then the comparison should move on to the name; you must do this, otherwise two different people with the same age will be considered to be the same Friend, which would be wrong.

The java.util.Arrays class provides methods that can be used to sort arrays. In your case, you'd use the version that takes an Object.

The java.util.Collections class provides methods for sorting a List. Storing your Friends in a List could be a good idea, to make it easier to add and remove entries.

Lastly, and possibly best, if you store your Friend objects in a SortedSet, they will always be kept in order automatically. You never actually have to sort them.
 
Ryan Maxwell
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!