Reputation: 3
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)
Upvotes: 0
Views: 120
Reputation: 1093
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]
Upvotes: 0
Reputation: 3
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:
Upvotes: 0
Reputation: 544
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)
Upvotes: 0