Home >Backend Development >Python Tutorial >How to implement python bubble sort algorithm?
Bubble sort is a simple sorting technique that traverses the entire list by comparing adjacent elements, sorting them and exchanging elements until the entire list is sorted.
Algorithm: Given a list L containing n elements, the values or records of these elements are L0, L1,...,Ln-1, bubble sorting is used Sort the list L.
Compare the first two elements in the list, L0 and L1.
If L1
Repeat the same steps until the entire list is sorted so that no more swaps are possible.
Return the final sorted list.
python bubble sort code is as follows:
__author__ = 'Avinash' def bubble_sort(sort_list): for j in range(len(sort_list)): for k in range(len(sort_list) - 1): if sort_list[k] > sort_list[k + 1]: sort_list[k], sort_list[k + 1] = sort_list[k + 1], sort_list[k] print(sort_list) lst = [] size = int(input("Enter size of the list: \t")) for i in range(size): elements = int(input("Enter the element: \t")) lst.append(elements) bubble_sort(lst)
Output:
Related recommendations: "Python Tutorial"
This article is an introduction to the python bubble sorting algorithm. I hope it will be helpful to friends in need!
The above is the detailed content of How to implement python bubble sort algorithm?. For more information, please follow other related articles on the PHP Chinese website!