Regarding in-place merge in an array

前端 未结 3 760
天涯浪人
天涯浪人 2020-12-01 08:37

I came across the following question.

Given an array of n elements and an integer k where k < n. Elements {a0

3条回答
  •  庸人自扰
    2020-12-01 08:57

    There are several algorithms for doing this, none of which are very easy to intuit. The key idea is to use a part of the arrays to merge as a buffer, then doing a standard merge using this buffer for auxiliary space. If you can then reposition the elements so that the buffer elements are in the right place, you're golden.

    I have written up an implementation of one of these algorithms on my personal site if you're interested in looking at it. It's based on the paper "Practical In-Place Merging" by Huang and Langston. You probably will want to look over that paper for some insight.

    I've also heard that there are good adaptive algorithms for this, which use some fixed-size buffer of your choosing (which could be O(1) if you wanted), but then scale elegantly with the buffer size. I don't know any of these off the top of my head, but I'm sure a quick search for "adaptive merge" might turn something up.

提交回复
热议问题