微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

对字典进行冒泡排序

如何解决对字典进行冒泡排序

我在实现冒泡、插入和选择排序时遇到问题。我不知道如何让整个事情奏效。请任何善良的灵魂

下面是添加到字典中的对象

items = {}
items[1] = Item(1,'Juicy',2,99,'New Zealand','Orange')
items[2] = Item(4,'Sweet','Thailand','Mango')
items[3] = Item(6,'Tasty & Sweet',4,'Malaysia','Bananas')
items[4] = Item(2,5,'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”是一个类,首先,你应该确保你启用了类实例的比较,使用方法: __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','Thailand','Mango']
items[3] = [6,'Tasty & Sweet',4,'Malaysia','Bananas']
items[4] = [2,5,'Australia','Watermelons']

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。