How can I sort a list in Python without the sort function?

205    Asked by Chandralekhadebbie in Python , Asked on Jan 12, 2024

 I am currently working on a particular project in which I need to organize a list of names of students based on the alphabet without using the function of sort() in the context of Python programming language. How can I do so? 

 In the context of Python programming language, if you aim to sort a list without using the sort function, then here are the codes given for this particular objective:-

Def bubble_sort(names):
    N = len(names)
    # Traverse through all elements in the list
    For I in range(n – 1):
        # Last I elements are already in place
        For j in range(0, n – I – 1):
            # Traverse the list from 0 to n – I – 1
            # Swap if the element found is greater
            # than the next element
            If names[j] > names[j + 1]:
                Names[j], names[j + 1] = names[j + 1], names[j]
# Example list of names
Students = [“Alice”, “Charlie”, “Bob”, “Eve”, “David”]
# Call the bubble sort function
Bubble_sort(students)
# Display the sorted list
Print(“Sorted list of names:”, students)

This above code defines a “custom sort” function which further executes the bubble sort algorithm for sorry the input list in ascending order. However, the original list would be unchanged, while the sorted list would be stored in the “sorted list”. Thus this particular approach doesn’t use the sort function, however, it achieves the sorting target.



Your Answer

Interviews

Parent Categories