这段代码是关于选择排序的,但是当我 运行 代码没有按预期工作时

This code is about Selection sorting but when i run the code it is not working as expected

该程序仅在没有。元素数为 2 如果大于 2 则不起作用。

#Selection Sort
L = []
n = int(input('Enter the number of elements\t:'))
for i in range(n):
    item = int(input('Enter item\t:'))
    L.append(item)
    print('List\t:')
    for i in range(n-1):
        for j in range ((i+1),n-1):
            if (L[j]<L[i]):
                (L[j],L[i]) = (L[i],L[j])
print(L)

output1 output2

试试这个

enter code here
#Declare variable for selection sort
L = []
n = int(input('Enter the number of elements\t:'))
#iterate for add values
for i in range(n):
    item = int(input('Enter item\t:'))
    L.append(item)
    print('List\t:')
#iterate for select minimun value and swap value in the array    
for i in range(len(L)):
    # Find the minimum element in remaining 
    # unsorted array
    min_idx = i
    for j in range(i+1, len(L)):
        if L[min_idx] > L[j]:
            min_idx = j
              
    # Swap the found minimum element with 
    # the first element        
    L[i], L[min_idx] = L[min_idx], L[i]
print(L)
L = []
n = int(input('Enter the number of elements\t:'))
for i in range(n):
    item = int(input('Enter item\t:'))
    L.append(item)
    print('List\t:')
#First loop from 0 to n-1
for i in range(n-1):
    #second loop from 1 to n
    for j in range ((i+1),n):
        if (L[j]<L[i]):
            (L[j],L[i]) = (L[i],L[j])

print(L)

输入

Enter item      :5
List    :
Enter item      :2
List    :
Enter item      :3
List    :
Enter item      :1

输出

[1, 2, 3, 5]

代码:

#Selection Sort
L = []
n = int(input('Enter the number of elements\t:'))
for i in range(n):
    item = int(input('Enter item\t:'))
    L.append(item)
print('List\t:')
for i in range(n-1):
    for j in range ((i+1),n):
        if (L[j]<L[i]):
            (L[j],L[i]) = (L[i],L[j])
print(L)

输出:

Here