How to sort nearly sorted array in the fastest time possible? (Java)

前端 未结 10 2171
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 06:14

I have an array of values which is almost, but not quite sorted, with a few values displaced (say, 50 in 100000). How to sort it most efficiently? (performance is absolutely

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-30 06:37

    Smoothsort or Timsort are great algorithms, and would be sensible things to use.

    I'd add that what you might not realise is that the humble insertion sort is adaptive. Indeed, for really almost sorted lists, as you seem to have, my understanding (which i can't back up with a reference) is that it's faster than the more sophisticated algorithms. The problem is that if the input isn't almost-sorted, it rapidly degrades to O(n^2). Still, it's very simple to implement correctly, so if you know for sure that your input is always almost-sorted, it would be a good choice.

提交回复
热议问题