简体   繁体   English

Python中的冒泡排序未正确排序

[英]Bubble sort in Python not sorting properly

I have to implement bubble sort as a homework and my python script has to look for 2 command line parameters: 我必须将气泡排序作为一项家庭作业来实现,而我的python脚本必须查找2个命令行参数:

-f that specifies the file path of the input file that contains a number on each line that I have to sort using bubble sort; -f指定输入文件的文件路径,该文件路径的每一行都包含一个数字,我必须使用冒泡排序对其进行排序;

-p that, if specified, tells the script to print the sorted list of numbers in the command line. -p,如果指定,则告诉脚本在命令行中打印数字的排序列表。

Also, I have to implement the algorithm in situ , which means I have to only use one list/array/etc without allocating any other temporary list/array/etc or variable to hold one or a part of all the numbers to sort in the algorithm. 另外,我必须在原位实现算法,这意味着我只需要使用一个列表/数组/等,而无需分配任何其他临时列表/数组/等或变量来容纳所有数字中的一个或一部分以进行排序。算法。 So, in my script, I only use unsortedList and nothing else to hold the numbers to sort. 因此,在我的脚本中,我只使用unsortedList,而没有其他东西来保存要排序的数字。 I have taken the bubble sort algorithm from the following link: Bubble Sort Homework . 我从以下链接中获取了冒泡排序算法: 冒泡排序作业

Here is my script: 这是我的脚本:

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:])

I am having 2 problems with my script: 我的脚本有2个问题:

First, if I do not specify the -f parameter, the script never runs the usage() function, it only tells "No such file or directory: ''". 首先,如果我未指定-f参数,该脚本将永远不会运行usage()函数,它只会告诉“没有这样的文件或目录:”。 Why isn't my script running the usage() function? 为什么我的脚本没有运行usage()函数?

Also, the bubble sort algorithm doesn't seem to work properly. 而且,冒泡排序算法似乎无法正常工作。 If I run the script, the numbers aren't sorted properly. 如果我运行脚本,则数字排序不正确。 I can, for example, see 3998 before 403 in the list. 例如,我可以在列表中的403之前看到3998。 But, I have noticed that the numbers ARE sorted, but only from the left of the numbers. 但是,我注意到数字是排序的,但仅从数字的左侧开始。 For example, I can see 2553, 256, 2562. 256 is clearly not bigger than 2553, but if you take the number from the left, the third character from the left, 6, is bigger than the third character from the left of 2553, which is 5. 例如,我可以看到2553、256、2562。256显然不大于2553,但是如果您从左边算起数字,则左边第三个字符6大于2553左边的第三个字符,即5。

How can I solve those two problems? 我该如何解决这两个问题?

Thanks for your help. 谢谢你的帮助。

First, if I do not specify the -f parameter, the script never runs the usage() function, it only tells "No such file or directory: ''". 首先,如果我未指定-f参数,该脚本将永远不会运行usage()函数,它只会告诉“没有这样的文件或目录:”。 Why isn't my script running the usage() function? 为什么我的脚本没有运行usage()函数?

getopt() doesn't know which flags are required and which are optional. getopt()不知道哪些标志是必需的,哪些标志是可选的。 It merely checks that you don't pass unspecified flags or omit an argument if a flag requires one with : . 它仅检查您是否未传递未指定的标志,或者如果标志需要以下参数,则忽略该参数:

It's up to you to check that -f is passed in if you require it. 如果需要,您可以检查是否传入了-f


Also, the bubble sort algorithm doesn't seem to work properly. 而且,冒泡排序算法似乎无法正常工作。 If I run the script, the numbers aren't sorted properly. 如果我运行脚本,则数字排序不正确。 I can, for example, see 3998 before 403 in the list. 例如,我可以在列表中的403之前看到3998。 But, I have noticed that the numbers ARE sorted, but only from the left of the numbers. 但是,我注意到数字是排序的,但仅从数字的左侧开始。

That's because your code is actually sorting strings rather than numbers, so it's putting them in lexicographic order . 那是因为您的代码实际上是在对字符串而不是数字进行排序,因此会将它们按字典顺序排列 Try converting them to numbers when you read the file in: 读取以下文件时,请尝试将它们转换为数字:

unsortedList = [int(line.rstrip('\n')) for line in inputFile]
                ^^^^                 ^

Also, I have to implement the algorithm in situ , which means I have to only use one list/array/etc without allocating any other temporary list/array/etc or variable to hold one or a part of all the numbers to sort in the algorithm. 另外,我必须在原位实现算法,这意味着我只需要使用一个列表/数组/等,而无需分配任何其他临时列表/数组/等或变量来容纳所有数字中的一个或一部分以进行排序。算法。

In that case, I'd recommend removing the return statement from the bubble sort function. 在这种情况下,建议您从冒泡排序功能中删除return语句。 The best way to show that you're only using one array is not to create a second variable called sortedList . 显示仅使用一个数组的最好方法是不创建另一个名为sortedList变量。

bubble(unsortedList)

If your bubble sort call is simply that, without the assignment, then it's clear you must be modifying the original array. 如果您的冒泡排序调用只是没有分配的那个,那么很明显您必须修改原始数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM