- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有这个 python Heapsort-Code 是从网上的伪代码制作的。
但它给出了错误的结果。
def heapSortUp(a):
heapifyUp(a, len(a))
end = len(a)-1
while end > 0:
a[end], a[0] = a[0], a[end]
end -= 1
siftUp(a, 0, end)
return a
def heapifyUp(a, count):
end = 1
while end < count:
siftUp(a, 0, end)
end += 1
def siftUp(a, start, end):
child = end
while child > start:
parent = int(math.floor((child-1)/2)) # floor = abrunden
if a[parent] < a[child]:
a[parent], a[child] = a[child], a[parent]
child = parent
else:
return
我特别想用 siftUP 版本。
通过计算 print heapSortUp([1,5,4,2,9,8,7])
它返回:[8, 7, 9, 2, 1, 4, 5, 7, 5]
最佳答案
问题是你需要在 heapSortUp(a)
中向下而不是向上筛选
def heapSortUp(a):
heapifyUp(a, len(a))
end = len(a)-1
while end > 0:
a[end], a[0] = a[0], a[end]
end -= 1
siftDown(a, 0, end)
return a
您需要向下筛选的原因是向上筛选会使堆无效。这可以用一个简单的例子来说明。
取一个堆 4,3,2,1
。在这种排序的一次迭代之后,您将在末尾放置 4 个,在前面放置 1 个。所以堆看起来像一棵树
1
3 2
然而,当您向上筛选时,您交换了 1
和 2
。这意味着 2 比 3 具有更高的优先级。如果您继续进行排序(如所写),您将排列数组 1,3,2,4
要获得实际的排序,您需要筛选一个,以便堆看起来像第一次迭代后的样子。
3
1 2
我将 siftDown 的实现留给你。
关于python - 为什么我的堆排序不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16574962/
今天有小伙伴给我留言问到,try{...}catch(){...}是什么意思?它用来干什么? 简单的说 他们是用来捕获异常的 下面我们通过一个例子来详细讲解下
我正在努力提高网站的可访问性,但我不知道如何在页脚中标记社交媒体链接列表。这些链接指向我在 facecook、twitter 等上的帐户。我不想用 role="navigation" 标记这些链接,因
说现在是 6 点,我有一个 Timer 并在 10 点安排了一个 TimerTask。之后,System DateTime 被其他服务(例如 ntp)调整为 9 点钟。我仍然希望我的 TimerTas
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我就废话不多说了,大家还是直接看代码吧~ ? 1
Maven系列1 1.什么是Maven? Maven是一个项目管理工具,它包含了一个对象模型。一组标准集合,一个依赖管理系统。和用来运行定义在生命周期阶段中插件目标和逻辑。 核心功能 Mav
我是一名优秀的程序员,十分优秀!