【问题标题】:Bubble sort a dictionary冒泡排序字典
【发布时间】: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


【解决方案1】:

如果“Item”是一个类,首先,你应该确保你启用了类实例的比较,使用方法: __le__, __ge__ 等等,其次,我认为你的字典中的第一个索引有一些问题, 等于 1,但是在排序时你从 0 开始计数,在你的位置我会为插入排序编写以下代码:

def insertion(theSeq):
    n = len(theSeq)
    for i in range(1, n + 1):
        pos = i
        while pos > 1 and theSeq[pos] < theSeq[pos - 1]:
            theSeq[pos], theSeq[pos - 1] = theSeq[pos - 1], theSeq[pos]
            pos -= 1

但我认为,主要问题是您无法比较“Item”类的实例,我已经在列表中使用参数运行了您的代码并且它成功了:

items = {}

items[1] = [1,'Juicy',2,99,'New Zealand','Orange']
items[2] = [4,'Sweet',2,99,'Thailand','Mango']
items[3] = [6,'Tasty & Sweet',4,99,'Malaysia','Bananas']
items[4] = [2,'Juicy',5,99,'Australia','Watermelons']

insertion(items)
for x in items.items():
    print(x)

【讨论】:

  • 非常感谢您,我会尝试使用您的方法,看看是否有效!谢谢!
猜你喜欢
  • 2015-08-08
  • 2013-10-09
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-26
  • 2015-03-06
相关资源
最近更新 更多