How to sort in-place using the merge sort algorithm?

前端 未结 10 1724
心在旅途
心在旅途 2020-11-22 02:21

I know the question is not too specific.

All I want is someone to tell me how to convert a normal merge sort into an in-place merge sort (or a merge sort with const

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 03:09

    The critical step is getting the merge itself to be in-place. It's not as difficult as those sources make out, but you lose something when you try.

    Looking at one step of the merge:

    [...list-sorted...|x...list-A...|y...list-B...]

    We know that the sorted sequence is less than everything else, that x is less than everything else in A, and that y is less than everything else in B. In the case where x is less than or equal to y, you just move your pointer to the start of A on one. In the case where y is less than x, you've got to shuffle y past the whole of A to sorted. That last step is what makes this expensive (except in degenerate cases).

    It's generally cheaper (especially when the arrays only actually contain single words per element, e.g., a pointer to a string or structure) to trade off some space for time and have a separate temporary array that you sort back and forth between.

提交回复
热议问题