我应该如何调整下面的选择排序代码以使其工作,同时看起来仍然有点相同? Python

How should I tweak the selection sort code below just enough to make it work while still looking a little the same? Python

下面的代码没有遍历列表并对列表进行排序。我应该如何调整它才能使其工作,同时看起来仍然有点相同?我尝试了多种方法使其无法正常工作。哦,我知道选择排序快捷方式 sort() 函数,但我还想了解如何编写函数、程序和进程的代码。谢谢!

def sortList(L,n):
    minValue = L[0]
    L2 = []
    idx = 0
    counter = 0
    
    while (counter < n):
        v = L[counter]
        if v < minValue:
            minValue = v
            idx = counter
            L2.append(minValue)
            del L[idx]
            n-=1

        counter += 1

    return L2

L = [34, -1, 0, 89, 21, -40, 7]
n = len(L)

print(sortList(L, n))

你可以实现插入排序:

def sortList(L):
    L2 = []
    
    while len(L) != 0:
        minValue = L[0]
        indx = 0 # index of the element that will be deleted
        counter = 0 # iterating counter
        for num in L:
            if num<minValue: 
                minValue = num
                indx=counter
            counter+=1
            
        L2.append(minValue)
        del L[indx]

    return L2

L = [34, -1, 0, 89, 21, -40, 7]

print(sortList(L))

或者您可以实现选择排序:

def sortList(L):
    
    for counter in range(0,len(L)):
        minValueIndex = counter

        for indx in range(counter,len(L)):
            if(L[indx] < L[minValueIndex]):
                minValueIndex = indx

        L[counter],L[minValueIndex] = L[minValueIndex],L[counter]

L = [34, -1, 0, 89, 21, -40, 7]

sortList(L)
print(L)

你的代码没有遵循选择排序逻辑(主要有两个错误:选择排序没有使用辅助排列,比如L2; 你没有改变当前的值(L[counter] ) 和较低的值 ( L[minValueIndex] ) 变量)。尝试在方法行上使用 print 来尝试理解算法的逻辑错误。

import sys
def selection_sort(unsorted_list):
    """Traverses the list to finds the min and inserts it in the beginning. 
    Then repeats traversing through the unsorted members, 
    each time popping and inserting the min after the previous mins."""

    my_list = list(unsorted_list)
    counter = 0
    j = 0
    while j < len(my_list):
        min = sys.maxsize
        min_index = -1
        for i in range(j, len(my_list)):
            counter += 1
            if my_list[i] < min:
                min = my_list[i]
                min_index = i
        
        a = my_list.pop(min_index)
        my_list.insert(j, a)
        j += 1
    return my_list

print(selection_sort([34, -1, 0, 89, 21, -40, 7]))
#output: [-40, -1, 0, 7, 21, 34, 89]

我强烈建议使用嵌套循环,因为它更容易,但我决定试一试

make it work while still looking a little the same

def sortList(L,n):
    minValue = L[0]+1
    L2 = []
    idx = 0
    counter = 0

    while (len(L) > 0):
        v = L[counter]
        if v <= minValue:
            minValue = v
            idx = counter
            n-=1
        counter += 1
        if counter >= len(L):
            L2.append(minValue)
            del L[idx]
            counter = 0
            if len(L):
                minValue = L[0]

    return L2

L = [34, -1, 0, 89, 21, -40, 7]
n = len(L)

print(sortList(L, n))