Java - Collections.sort() performance

后端 未结 5 1397
孤街浪徒
孤街浪徒 2020-12-30 02:59

I\'m using Collections.sort() to sort a LinkedList whose elements implements Comparable interface, so they are sorted in a natural order. In the javadoc documentation its sa

5条回答
  •  醉话见心
    2020-12-30 03:38

    In terms of sorting the list, no, all comparison based sorts on general data are O(N log(N)).

    If your resorting is due to insertions, then you can try to batch your insertions and then merge sort with the main list - if you have B new items, you sort them in O(B log(B)) then do a single level merge of the two lists which is O(N+B).

    If your resorting is due to changes in the values of the items, you might be able to do a similar batching if you change the mutable values into immutable ones and treat the changes to be a batch of insertions and deletions. Otherwise, you won't be able to avoid sorting the whole list.

    If your requirements allow it, then there are various non-linked-list structures such as TreeSet available which maintain a sorted order more efficiently, but will fail if the values are mutable.

提交回复
热议问题