我应该如何调整下面的选择排序代码,使其在看起来有点相同的情况下工作?python

2022-12-01 04:07:13 发布

您现在位置: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))

Tags: 方法函数代码程序列表排序进程counter情况sort快捷方式idxl2minvaluesortlist
3条回答
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]

您可以实现插入排序:

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来理解算法的逻辑错误

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

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