python - python 中的冒泡排序帮助 - 升序和降序

标签 python algorithm bubble-sort

所以我是 python 的新手,我有一个项目需要我们通过一个非常长的元组列表,我们必须按降序和升序对列表进行排序。但是,对于我的两个功能,我总是按升序排列,怎么了?有人请帮助我真的很紧张

def bubblesort_descending(tuple_list):
    j = len(tuple_list)
    made_swap = True
    swaps = 0
    while made_swap:
        made_swap = False
        for cnt in range (j-1):
            if tuple_list[cnt] < tuple_list[cnt+1]:
                tuple_list[cnt], tuple_list[cnt+1] = tuple_list[cnt+1], tuple_list[cnt]
                made_swap = True
                swaps = swaps + 1
    return swaps

主程序:

elif choice ==  'd':
    unsorted = range(len(numbers))
    shuffle(unsorted)
    print ("Randomised tuple list generated:")
    print
    print (unsorted)

    swaps = bubblesort_descending (unsorted)
    print
    print ("heres the sorted list")
    print
    print (unsorted)
    print
    print (swaps, "swap(s) made")
    print

最佳答案

升序降序排序顺序的基本区别在于比较:这是一个冒泡排序实现取自 http://www.codecodex.com/wiki/Bubble_sort#Python :

def bubble_sort(lst, asc=True):
    lst = list(lst)  # copy collection to list
    for passesLeft in range(len(lst)-1, 0, -1):
        for i in range(passesLeft):
            if asc:
                if lst[i] > lst[i + 1]:
                    lst[i], lst[i + 1] = lst[i + 1], lst[i]
            else:
                if lst[i] < lst[i + 1]:
                    lst[i], lst[i + 1] = lst[i + 1], lst[i]
    return lst

注意:区别基于asc参数?

示例:

>>> xs = [1, 2, 9, 4, 0]
>>> bubble_sort(xs, asc=True)
[0, 1, 2, 4, 9]
>>> bubble_sort(xs, asc=False)
[9, 4, 2, 1, 0]

所以实际上交换了你的逻辑运算符 <>反转排序顺序。

关于python - python 中的冒泡排序帮助 - 升序和降序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21152778/

相关文章:

python - 需要帮助诊断 Python/MySQL 插入/更新异常

multithreading - Lamport 的面包店算法

c++ - 在自定义冒泡排序实现中比较迭代器崩溃程序而没有错误

java - 我的冒泡排序似乎运行了太多次,或者向后运行

python - 为什么 xml.etree.ElementTree 方法 findtext() 将\r\n 转换为\n?

Python 在运行时更改日志文件位置

python - 在 Python 中调用 AutoIt 函数

algorithm - 遗传算法 - 更好的交叉/变异算法?

c++ - 偶数和奇数位置元素之和的最大差值 : How to memoize the brute-force approach?

c++ - 这是什么类型的?