Selection sort program python

前端 未结 2 1863
有刺的猬
有刺的猬 2021-01-28 17:11

So this is supposed to be a sorting program, but for some reason, it is not sorting the file I\'m giving, but just giving me straight numbers as it is. Any help would be appreci

2条回答
  •  清歌不尽
    2021-01-28 17:34

    You didn't call the function!

    def selectionSort(alist):
        for index in range(0, len(alist)):
            ismall = index
            for i in range(index,len(alist)):
                if alist[ismall] > alist[i]:
                    ismall = i
            alist[index], alist[ismall] = alist[ismall], alist[index]
    
    filename=input('Enter file path:')
    file = open(filename, 'r')
    alist = file.readlines()
    
    # Call the function!
    selectionSort(alist)
    print(alist)
    

    You've told Python what selectionSort means, but you haven't told it to sort anything. You need to call selectionSort(alist) to actually perform the sort.

    Also, the order you want the list to be sorted in is most likely not the order you're telling Python to sort it in. alist is a list of strings, so you're telling Python to use lexicographic comparison to order the list. If it's supposed to be treated as, say, integers, you need to convert the data to integers:

    alist = [int(line) for line in file]
    

    (Also, since selectionSort modifies the list it operates on, it's best not to return the list. If you return it, it gives the impression that it creates a new, sorted list.)

提交回复
热议问题