简体   繁体   中英

Using compareTo() to sort a LinkedList alphabetically?

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.

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.

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:

  • If an object closer to the front of the list is compared to an object further away from the front, and the result is negative or zero, the objects are in a proper order in relation to each other
  • If the result is positive, the objects should change places so that the one further away from the start would be closer to the start.

These two considerations alone are sufficient to implement bubble sort .

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM