Python中的冒泡排序没有正确排序

Cho*_*890 0 python sorting algorithm bubble-sort

我必须实现冒泡排序作为家庭作业,我的python脚本必须查找2个命令行参数:

-f指定输入文件的文件路径,该文件路径包含每行必须使用冒泡排序排序的数字;

-p,如果指定,则告诉脚本在命令行中打印已排序的数字列表.

此外,我必须在原位实现该算法,这意味着我必须只使用一个列表/数组/ etc而不分配任何其他临时列表/数组/ etc或变量来保存所有数字的一个或一部分以在算法.因此,在我的脚本中,我只使用unsortedList而没有其他任何东西来保存要排序的数字.我从以下链接中获取了冒泡排序算法:冒泡排序作业.

这是我的脚本:

import sys, getopt

def main(argv):
    inputFilePath = ""
    printList = False

    # Traitement pour parser les arguments
    try:
        opts, args = getopt.getopt(argv, "f:p")
    except getopt.GetoptError:
        usage()
        sys.exit()
    for opt, arg in opts:
        if opt in ("-f"):
            inputFilePath = arg
        if opt in ("-p"):
            printList = True

    inputFile = open(inputFilePath, "r")
    unsortedList = [line.rstrip('\n') for line in inputFile]

    sortedList = bubble(unsortedList)
    if printList == True:
        print (sortedList)

def usage():
    print ("""
    Usage: bubble.py -f <filepath> -p
           -f <filepath> [REQUIRED]: specifies the filepath of the input file
           -p            [OPTIONAL]: specifies whether to print the sorted list or not
    """)

# Function found at https://stackoverflow.com/questions/895371/bubble-sort-homework
def bubble(unsortedList):
    length = len(unsortedList) - 1
    isSorted = False

    while not isSorted:
        isSorted = True
        for i in range(length):
            if unsortedList[i] > unsortedList[i+1]:
                isSorted = False
                unsortedList[i], unsortedList[i+1] = unsortedList[i+1], unsortedList[i]

    return unsortedList

if __name__ == "__main__":
    main(sys.argv[1:])
Run Code Online (Sandbox Code Playgroud)

我的脚本有2个问题:

首先,如果我没有指定-f参数,脚本永远不会运行usage()函数,它只会告诉"没有这样的文件或目录:''".为什么我的脚本不运行usage()函数?

此外,冒泡排序算法似乎无法正常工作.如果我运行脚本,则数字排序不正确.例如,我可以在列表中的403之前看到3998.但是,我注意到数字是排序的,但只是从数字的左边开始.例如,我可以看到2553,256,2562.256显然不大于2553,但是如果你从左边取数字,左边的第三个字符6比2553左边的第三个字符大,这是5.

我该如何解决这两个问题?

谢谢你的帮助.

Joh*_*ica 5

首先,如果我没有指定-f参数,脚本永远不会运行usage()函数,它只会告诉"没有这样的文件或目录:''".为什么我的脚本不运行usage()函数?

getopt()不知道哪些标志是必需的,哪些是可选的.它只是检查你没有传递未指定的标志,或者如果一个标志需要一个,则省略一个参数:.

-f如果您需要,可以检查是否传入.


此外,冒泡排序算法似乎无法正常工作.如果我运行脚本,则数字排序不正确.例如,我可以在列表中的403之前看到3998.但是,我注意到数字是排序的,但只是从数字的左边开始.

那是因为你的代码实际上是排序字符串而不是数字,所以它将它们按字典顺序排列.在您阅读文件时尝试将它们转换为数字:

unsortedList = [int(line.rstrip('\n')) for line in inputFile]
                ^^^^                 ^
Run Code Online (Sandbox Code Playgroud)

此外,我必须在原位实现该算法,这意味着我必须只使用一个列表/数组/ etc而不分配任何其他临时列表/数组/ etc或变量来保存所有数字的一个或一部分以在算法.

在这种情况下,我建议从冒泡排序功能中删除return语句.显示您只使用一个数组的最佳方法是不创建名为的第二个变量sortedList.

bubble(unsortedList)
Run Code Online (Sandbox Code Playgroud)

如果您的冒泡排序调用只是那个,没有赋值,那么很明显您必须修改原始数组.