Sorted List and compareTo
A sorted list maintains the invariant that consecutive elements are in non-decreasing order with respect to a given order. Insertion searches for the position and appends the node.
In Java, Comparable.compareTo provides the natural order. Comparator allows an external order without having to change the element class.
Example: Inserting 5 into 1-3-8 results in 1-3-5-8.
Complexity: Search $O(n)$ in the linked list, followed by $O(1)$ for rearranging.
Where used
Small sorted collections, merging streams, priorities without a full heap, when n remains small. compareTo/Comparator is the same order that TreeMap, sorting, and PriorityQueue use.
Depth
A sorted list maintains the invariant after each modification that consecutive elements do not decrease according to the comparison relation. The insertion position is the first place where the new element is no longer greater than the current value.
compareTo returns a negative, zero, or positive result. The specific magnitude has no portable meaning. A consistent order should be transitive and antisymmetric in sign; otherwise, searching and inserting can yield contradictory positions.
In a linked structure, the search for the position remains linear. Sorting does not improve random access there but can enable early termination during searching and ordered merging of two lists.
Difficulty levels
- Correctly interpreting the sign of comparison results.
- Determining an insertion position under duplicate rules.
- Analyzing sequences of a non-transitive comparison relation.
Pitfalls
Code must not assume that the result is exactly -1, 0, or 1. Additionally, an order that is inconsistent with equals can produce surprising duplicate semantics.
Tasks
Card Info
- Topic: Algorithms and Data Structures
- Difficulty: Intermediate
- Completed: 0 users