简体   繁体   English

选择排序(从低到高)python

[英]Selection Sort (low to high) python

I am trying to write a selection sort algorithm for sorting lists of numbers from lowest to highest. 我正在尝试编写一种选择排序算法,用于从最低到最高对数字列表进行排序。

def sortlh(numList):
    if type(numList) != list:
        print("Input must be a list of numbers.")
    else:
        inf = float("inf")
        sortList = [0]*len(numList)
        count = 0
        while count < len(numList):          
            index = 0
            indexLowest = 0
            lowest = numList[index]
            while index < (len(numList) - 1):
                if numList[index + 1] < numList[index]:
                    lowest = numList[index + 1]
                    indexLowest = index + 1
                    index = index + 1
                else:
                    index = index + 1
            sortList[count] = lowest
            numList[indexLowest] = inf
            count = count + 1
    return sortList

When I run this code on: 当我在以下代码上运行此代码时:

sortlh([9,8,7,6,5,4,3,2,1])

I get (as expected): 我得到(如预期):

[1, 2, 3, 4, 5, 6, 7, 8, 9]

However, when I try another example, I get: 但是,当我尝试另一个示例时,我得到:

sortlh([1,3,2,4,5,7,6,9,8])

[8, 6, 9, 2, 4, 5, 7, 1, 3] [8、6、9、2、4、5、7、1、3]

Does anyone see what is going on here? 有人看到这里发生了什么吗?

Here is how I would suggest rewriting your program. 这是我建议重写程序的方式。

def sortlh(lst_input):
    lst = list(lst_input) # make a copy of lst_input
    i = 0
    while i < len(lst):
        j = i + 1
        i_lowest = i
        lowest = lst[i_lowest]
        while j < len(lst):
            if lst[j] < lowest:
                i_lowest = j
                lowest = lst[i_lowest]
            j += 1
        lst[i], lst[i_lowest] = lst[i_lowest], lst[i]  # swap
        i += 1
    return lst

test = [9,8,7,6,5,4,3,2,1]
assert sortlh(test) == sorted(test)
test = [1,3,2,4,5,7,6,9,8]
assert sortlh(test) == sorted(test)
  • We don't test the type of the input. 我们不测试输入的类型。 Anything that acts like a list will work, and even an iterator will work. 任何像列表一样的东西都可以使用,甚至迭代器也可以使用。

  • We don't "mutate" the original input list. 我们不会“突变”原始输入列表。 We only work on a copy of the data. 我们仅处理数据副本。

  • When we find the lowest number, we swap it with the first number, and then only look at the remaining numbers. 找到最低编号后,我们将其与第一个编号交换,然后仅查看其余编号。 Thus we have less work to do on each loop as we have fewer and fewer unsorted numbers. 因此,由于未排序的数字越来越少,因此每个循环上要做的工作更少。

EDIT: 编辑:

If you are a beginner, this part might seem too tricky. 如果您是初学者,这部分可能看起来太棘手。 If it confuses you or you don't like it, just ignore it for now. 如果它使您感到困惑或您不喜欢它,请暂时将其忽略。

This is a more-advanced way to solve this problem in Python. 这是在Python中解决此问题的更高级的方法。 The inner loop simply finds the lowest number and the index of the lowest number. 内部循环仅查找最低编号和最低编号的索引。 We can use the Python built-in function min() to do this! 我们可以使用Python内置函数min()做到这一点!

We build a "generator expression" that loops over the list, yielding up tuples. 我们构建了一个“生成器表达式”,该表达式在列表上循环,生成元组。 Each tuple is the number and its position. 每个元组是数字及其位置。 Since we want lower numbers to sort lower, we put the number first in the tuple so that min() can properly compare the tuples. 由于我们希望较低的数字排序较低,因此我们将数字放在元组的第一位,以便min()可以正确比较元组。 Then min() will find the lowest tuple and we get the value and index. 然后, min()将找到最低的元组,然后得到值和索引。

Also, the outer loop is now a for loop with enumerate rather than a while loop using indexing. 而且,外部循环现在是带有enumeratefor循环,而不是使用索引的while循环。

def sortlh(lst_input):
    lst = list(lst_input) # make a copy of lst_input
    for i, x in enumerate(lst):
        lowest, i_lowest = min((n, j) for j, n in enumerate(lst) if j >= i)
        lst[i], lst[i_lowest] = lst[i_lowest], lst[i]  # swap
    return lst

test = [9,8,7,6,5,4,3,2,1]
assert sortlh(test) == sorted(test)
test = [1,3,2,4,5,7,6,9,8]
assert sortlh(test) == sorted(test)

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

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