Advertisements
Advertisements
Question
Sort a list containing names of students in ascending order using selection sort.
Code Writing
Advertisements
Solution
The program finds the alphabetically smallest name from the unsorted portion and swaps it into the correct position.
def selection_sort_names(names):
for i in range(len(names) - 1):
minimum_index = i
# Find alphabetically smallest name
for j in range(i + 1, len(names)):
if names[j].lower() < names[minimum_index].lower():
minimum_index = j
# Place the smallest name at index i
names[i], names[minimum_index] = names[minimum_index], names[i]
return names
students = input("Enter student names separated by commas: ").split(",")
students = [name.strip() for name in students]
print("Sorted names:", selection_sort_names(students))
Enter student names separated by commas: Neena, Meeta, Geeta, Reeta
Sorted names: ['Geeta', 'Meeta', 'Neena', 'Reeta']shaalaa.com
Is there an error in this question or solution?
