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

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

    As Botz3000 noted, you can't perform such an operation faster than O(N). The most basic element of any algorithm would be to find those entries in the array that are out of order. This requires O(N), even before you figure out what to do with them.

    If indeed the number of "out-of-order" elements is orders of magnitude below the total number of elements, you could use the following algorithm (assuming linked list):

    1. Find all out-of-order items and extract the from the original list to a separate list, O(N)
    2. The result is two lists: a sorted list and a short extracted list
    3. For each of the extracted elements, insert them into the sorted list. That would be O(log(N)) for each, total is O(Xlog(N)), where X is the number of the extracted elements. If X is very small relative to N, you end up with a total of O(N).

提交回复
热议问题