Sorting an almost sorted array (elements misplaced by no more than k)

后端 未结 5 1973
灰色年华
灰色年华 2020-12-07 07:46

I was asked this interview question recently:

You\'re given an array that is almost sorted, in that each of the N elements may be misplac

5条回答
  •  攒了一身酷
    2020-12-07 08:37

    Your solution is a good one if k is large enough. There is no better solution in terms of time complexity; each element might be out of place by k places, which means you need to learn log2 k bits of information to place it correctly, which means you need to make log2 k comparisons at least--so it's got to be a complexity of at least O(N log k).

    However, as others have pointed out, if k is small, the constant terms are going to kill you. Use something that's very fast per operation, like insertion sort, in that case.

    If you really wanted to be optimal, you'd implement both methods, and switch from one to the other depending on k.

提交回复
热议问题