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)
CodePudding user response:
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]
CodePudding user response:
try this
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)
CodePudding user response:
Code:
#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)
Output: