合并排序:是否需要额外的数组副本?

发布于 2024-10-04 18:54:44 字数 366 浏览 0 评论 0原文

在“算法简介”中,合并排序算法是通过名为 MERGE(A, p, q, r) 的辅助函数实现的 - 该函数合并两个先前排序的序列。

此函数引入了两个附加数组 LR

MERGE(A, p, q, r)
1 n1 ← q − p + 1
2 n2 ←r − q
3 create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1]
.....

通过“创建数组 L[1 . . n1 + 1] 和 R[1 . . n2 + 1]” 我理解为它们分配额外的内存。

是否可以重写这个函数,这样我就不需要额外的内存,并直接操作 A ?

In "Introduction to Algorithms" the merge sort algorithm is implemented with a helper function called MERGE(A, p, q, r) - that is merging two previously sorted sequences .

This function introduces two additional arrays L and R .

MERGE(A, p, q, r)
1 n1 ← q − p + 1
2 n2 ←r − q
3 create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1]
.....

By "create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1]" I understand to allocate additional memory for both of them .

Is it possible to re-write this function, so that I won't need the additional memory, and to operate directly to A ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

画离情绘悲伤 2024-10-11 18:54:44

当然。它称为就地合并排序。

维基百科说它很复杂 - 但事实并非总是如此。 有些并不像其他,如果您不关心运行时

有一些变化,有些是稳定的,有些是不稳定的。有关示例,请参阅 NIST DIAGS 下的“实现”部分。

Sure. It is called in-place merge sort.

Wikipedia say it is complicated -- but it is not always true. Some are not as complicated as others, if you don't care about the run-time.

There are a few variance, some are stable, some are non-stable. See the "implementation" section under NIST DIAGS for some example.

内心激荡 2024-10-11 18:54:44

是的,它被称为就地合并排序,但正如 Wikipedia 所说:

就地排序是可能的(例如,使用列表而不是数组),但非常复杂,并且在实践中几乎不会带来性能提升,即使算法运行时间为 O(n log n) 。 (Katajainen、Pasanen 和 Teuhola 1996)

Yes, it's called in-place merge sort, but as Wikipedia puts it:

Sorting in-place is possible (e.g., using lists rather than arrays) but is very complicated, and will offer little performance gains in practice, even if the algorithm runs in O(n log n) time. (Katajainen, Pasanen & Teuhola 1996)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文