空间复杂度问题
Possible Duplicate:
Regarding in-place merge in an array
I have an array, where the first and second half of the array is sorted, e.g.
A[] = "2 4 7 1 5 20"
No how do I sort the whole array in O(1) space complexity?
Regards,
Mithun
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
查看此列表,并从具有以下功能的算法中进行选择: “内存”列中的“
1
”。如果您唯一的要求是恒定的辅助空间,没有其他效率要求,则数组已经具有某种顺序的事实是无关紧要的。Take a look at this list, and take your pick from any of the algorithms that have '
1
' in the 'Memory' column. The fact that the array has some sort of order already is irrelevant if your only requirement is constant auxiliary space, with no other efficiency requirements.这对我来说是一种尖叫的合并排序(为了时间效率),我认为它没有一个很好的就地算法(O(1) 空间)。您可以查看这个问题 - 地方合并排序。
我同意 Ani 的观点,如果你确实需要 O(1) 空间,那么使用 快速排序。
This screams merge sort (for time efficiency) to me which I don't think has a nice in-place algorithm (O(1) space). You could see this question for an in-place merge sort.
I agree with Ani, if you really need O(1) space it will probably be easier to just use something like quicksort.
使用伪代码,这是一个就地两个堆栈合并。
它通过维持以下不变量来工作(应该工作): A[1..mid] 和 A[mid..n] 已排序,并且 A[1..i] 包含的元素严格小于 A[ 中包含的元素中..n]。我可能搞砸了细节,但这是基本想法。
Using pseudo code, here is an in-place two stack merge.
It works (is supposed to work) by maintaining the follow invariant: A[1..mid] and A[mid..n] are sorted, and A[1..i] contains elements strictly less than those contained in A[mid..n]. I might have botched the details, but that is the basic idea.
我(当然)可能是错的,但我猜任何只需要 O(1) 空间的东西也将具有 O(N2) 复杂性。尽管如此,我认为您可以比仅仅应用普通插入排序做得更好(一点)。
I could (of course) be wrong, but I'd guess anything that takes only O(1) space will also have O(N2) complexity. Nonetheless, I think you can do a (little) bit better than just applying a normal insertion sort.