3.1.5.3 Sorting simple lists - the bubble sort algorithm
The bubble sort - interactive version
In the editor you can see a complete program, enriched by a conversation with the user, and allowing the user to enter and to print elements from the list: The bubble sort - final interactive version.
Python, however, has its own sorting mechanisms. No one needs to write their own sorts, as there is a sufficient number of ready-to-use tools.
We explained this sorting system to you because it's important to learn how to process a list's contents, and to show you how real sorting may work.
If you want Python to sort your list, you can do it like this:
myList = [8, 10, 6, 2, 4]
myList.sort()
print(myList)
It is as simple as that.
The snippet's output is as follows:
[2, 4, 6, 8, 10]
As you can see, all the lists have a method named
sort()
, which sorts them as fast as possible. You've already learned about some of the list methods before, and you're going to learn more about others very soon.How many elements do you want to sort:
How many elements do you want to sort: 4
Enter a list element: 4
Enter a list element: 5
Enter a list element: 8
Enter a list element: 9
Sorted:
[4.0, 5.0, 8.0, 9.0]
Comments
Post a Comment