【发布时间】:2021-08-18 01:02:27
【问题描述】:
我在实现冒泡、插入和选择排序时遇到问题。我不知道如何使整个事情起作用。任何善良的灵魂都请
下面是添加到字典中的对象
items = {}
items[1] = Item(1,'Juicy',2,99,'New Zealand','Orange')
items[2] = Item(4,'Sweet',2,99,'Thailand','Mango')
items[3] = Item(6,'Tasty & Sweet',4,99,'Malaysia','Bananas')
items[4] = Item(2,'Juicy',5,99,'Australia','Watermelons')
以下是排序功能,但无法排序
def bubble(theSeq):
n = len(theSeq)
for i in range(1, n):
for j in range(n - i):
if theSeq[j] > theSeq[j + 1]:
tmp = theSeq[j]
theSeq[j] = theSeq[j + 1]
theSeq[j + 1] = tmp
def selection(theSeq):
n = len(theSeq)
for i in range(n - 1):
smallNdx = i # 0
for j in range(i + 1, n):
if theSeq[j] > theSeq[smallNdx]:
smallNdx = j
if smallNdx != i:
tmp = theSeq[i]
theSeq[i] = theSeq[smallNdx]
theSeq[smallNdx] = tmp
def insertion(theSeq):
n = len(theSeq)
for i in range(0, n):
value = theSeq[i]
pos = i
while pos > 0 and value < theSeq[pos - 1]:
theSeq[pos] = theSeq[pos - 1]
pos -= 1
theSeq[pos] = value
【问题讨论】:
-
没有看到 Item 类,我们怎么知道它们是如何比较的?
-
你好!一些东西。首先,重要的是要注意您的排序函数处理“0”索引(“范围”函数从零开始),并且索引中不存在该索引。同样重要的是要提到您正在比较此“项目”类的实例。对于自定义类,您必须决定如何比较它们(即,当它们之间存在“programiz.com/python-programming/operator-overloading
标签: python bubble-sort insertion-sort selection-sort