Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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:')
for i in range(n):
    #First loop from 0 to n-1
    for k in range(n-1):
        #second loop from 1 to n
        for j in range ((k+1),n):
            if (L[j]<L[k]):
                (L[j],L[k]) = (L[k],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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading