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

后端 未结 5 1987
灰色年华
灰色年华 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:36

    If using only the comparison model, O(n log k) is optimal. Consider the case when k = n.

    To answer your other question, yes it is possible to do this without sorting, by using heaps.

    Use a min-heap of 2k elements. Insert 2k elements first, then remove min, insert next element etc.

    This guarantees O(n log k) time and O(k) space and heaps usually have small enough hidden constants.

提交回复
热议问题