Home >Backend Development >Python Tutorial >How to implement python bubble sort algorithm?

How to implement python bubble sort algorithm?

藏色散人
藏色散人Original
2019-02-27 14:23:4124909browse

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.

How to implement python bubble sort algorithm?

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:

How to implement python bubble sort algorithm?

How to implement python bubble sort algorithm?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn