当负数位于数组的右端时,选择排序算法不起作用

Selection Sort Algorithm Not Working When Negative Number Is At Right End of Array

我早些时候看到 post 有人说解决方案是不要在内部 for 循环之外进行交换。下面的算法没有,但仍然不适用于列表 A 仅 B

A = [4,2,7,-8,1,3,8,6,-1,-2]
B = [3,4,2,5,3,21,-7,3,26,-43,-12,22]

def selection_sort(list):
    
    for i in range(len(list)-1):
        smallest_index = i
        #print('i: ', list[i])
        for j in range(i+1,len(list)-1):
            if list[j] < list[smallest_index]:
                smallest_index = j
                #print('j: ', list[j])

        
        if smallest_index != i:
            list[i], list[smallest_index] = list[smallest_index], list[i]
                 
    
    return list

selection_sort(B)  

A 的结果

[-43, -12, -7, 2, 3, 3, 3, 4, 5, 21, 22, 26, -2]

你的两个 for 循环的边界都是错误的;两个循环的上限应该是 len(list) 而不是 len(list) - 1。 (请记住,range() 的上限是互斥的。)

这对输入进行了正确排序:

B = [3,4,2,5,3,21,-7,3,26,-43,-12,22]

# Don't use list as a variable name; it shadows the list() builtin.
def selection_sort(input_list):
    for i in range(len(input_list)):
        smallest_index = i
        for j in range(i+1, len(input_list)):
            if input_list[j] < input_list[smallest_index]:
                smallest_index = j

        if smallest_index != i:
            input_list[i], input_list[smallest_index] = \
                input_list[smallest_index], input_list[i]
                 
    return input_list

print(selection_sort(B))