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

前端 未结 10 2112
没有蜡笔的小新
没有蜡笔的小新 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:59

    There are many good algorithms for this.

    Smoothsort is my personal favorite... I actually worked all the math out here if you're curious why it works so well.

    A fairly good algorithm for already-sorted data is natural mergesort, which is a bottom-up version of mergesort that works by treating the input as a sequence of sorted subranges, then making multiple passes over the range merging adjacent sorted ranges. It runs in O(n) time if the data is already sorted (because it can detect that there's only one sorted range), and O(n lg n) in the worst case. This algorithm works quite well if the data is "block sorted"; that is, it consists of a lot of sorted blocks placed right next to one another.

    Straight insertion sort definitely works well for mostly-sorted data, but can degenerate very badly on a lot of inputs. Some really good sorts (like introsort) actually use this property of insertion sort to do a "cleanup step" on the input.

提交回复
热议问题