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

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

    As Bob Sedgewick showed in his dissertation work (and follow-ons), insertion sort absolutely crushes the "almost-sorted array". In this case your asymptotics look good but if k < 12 I bet insertion sort wins every time. I don't know that there's a good explanation for why insertion sort does so well, but the place to look would be in one of Sedgewick's textbooks entitled Algorithms (he has done many editions for different languages).

    • I have no idea whether O(N log k) is optimal, but more to the point, I don't really care—if k is small, it's the constant factors that matter, and if k is large, you may as well just sort the array.

    • Insertion sort will nail this problem without re-sorting the same elements.

    Big-O notation is all very well for algorithm class, but in the real world, constants matter. It's all too easy to lose sight of this. (And I say this as a professor who has taught Big-O notation!)

提交回复
热议问题