Reputation: 121
I have a LinkedList which holds data for a student, it has a name, gpa, and ID# for each student, and each student is a Node in the LinkedList. I want to sort my LinkedList alphabetically by their names, but I'm not really understanding how to use CompareTo() to sort. So right now I have my compareTo method using the string compareTo of the current name.compareTo(name_of_inputStudent). So in my sort method how would i utilize that output to sort my array? I don't really understand how that would help me identify which string belongs in which position on the LinkedList.
Upvotes: 2
Views: 2584
Reputation: 516
In you Node class of the LinkedList, implement Comparable interface and override compareTo method. Then you can use Collections.sort(List). Since you are using a linked list, sorting will be inefficient as getting an element in a LinkedList is a sequential traversal that is, O(n).
Upvotes: 0
Reputation: 727067
If you are allowed to use Java library, you don't have to do anything else: simply pass your list to sort
, which uses compareTo
automatically when you do not pass a separate comparer. Note that sorting a LinkedList
is more expensive than sorting an ArrayList
, because most advanced comparison-based sorting algorithms require random access to the list, which is O(1) for an array list, but O(n) for a linked list.
If you set on implementing your own sorting algorithm, compareTo
lets you determine if two objects are in a sorted position or if they should switch places:
These two considerations alone are sufficient to implement bubble sort.
Upvotes: 2
Reputation: 8353
You can use the method Collections.sort(...)
. You can find the javadoc here. To use the method your Student
class must implement Comparable
interface. So, you have to select a sorting criteria for your Student
class and implement it into the compareTo
method.
Upvotes: 2