Whimusical
Whimusical

Reputation: 6649

Does Collections.sort respect the index among the tied inputted elements? (Sorting Stability)

For example if I sort a List<Individual> with 10 people by Individual::Age, and I input Alice(3), Bob(5), and Charles(3), will the output be Alice(3), Charles(3), Bob(5) or is it possible for Alice and Charles being swapped in a way that they are outputed in a different sequence than the inputed?

Edit:
Seems that his property has a proper name: https://en.wikipedia.org/wiki/Sorting_algorithm#Stability

Upvotes: 3

Views: 83

Answers (3)

Kanagaraj M
Kanagaraj M

Reputation: 966

This is totally depends on how we implements our comparator(or comparable) class. If you are comparing only age then the order will be same as inserted(as List using merge sort) or if you are comparing both age and name then this will be in dictionary order.

Upvotes: 1

alvaro g
alvaro g

Reputation: 533

This depends on the stability of the sort algorithm: see wikipedia page

Depends on the JDK implementation

Upvotes: 1

Mureinik
Mureinik

Reputation: 311573

To quote the documentation:

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

For this purpose, Alice and Charles are equal (as they have the same age). Calling sort is guaranteed to keep their relative order, and Alice will appear before Charles.

Upvotes: 8

Related Questions