Computer Science

During admission in a course, the names of the students are inserted in ascending order. Thus, performing the sorting operation at the time of inserting elements in a list. Identify the type of sorting technique being used and write a program using a user defined function that is invoked every time a name is input and stores the name in ascending order of names in the list.

Python Sorting

6 Likes

Answer

The sorting technique being used in the program is Insertion Sort. In Insertion Sort, elements are sorted by inserting each element into its correct position in the sorted part of the list.

def insert_name(names_list, new_name):
    index = len(names_list)
    for i in range(index):
        if new_name < names_list[i]:
            index = i
            break
    names_list.insert(index, new_name)

names_list = []

while True:
    new_name = input("Enter a name (or 'exit' to stop): ")
    if new_name.lower() == 'exit':
        break
    insert_name(names_list, new_name)

print("Sorted list of names:")
for name in names_list:
    print(name)
Output
Enter a name (or 'exit' to stop): Amruth
Enter a name (or 'exit' to stop): Parth
Enter a name (or 'exit' to stop): Sanket
Enter a name (or 'exit' to stop): Shrestha
Enter a name (or 'exit' to stop): Nikita
Enter a name (or 'exit' to stop): exit
Sorted list of names:
Amruth
Nikita
Parth
Sanket
Shrestha

Answered By

4 Likes


Related Questions