Search code examples
pythonsortingselection-sort

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


The program only works when the no. of elements is 2 if it is more than 2 it doesn't work.

#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


Solution

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

    input

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

    output

    [1, 2, 3, 5]