Home  >  Article  >  Backend Development  >  Use python to implement 8 sorting algorithms-bubble sort

Use python to implement 8 sorting algorithms-bubble sort

巴扎黑
巴扎黑Original
2016-11-26 11:47:381223browse

The basic idea of ​​​​bubble sorting:

Bubble sorting is to visit two adjacent numbers in sequence and compare them (except for the last number) until the sorting is completed.

Example:

arr = [49,38,04,97,76,13,27,49,55,65], exchange

arr = [38,49,04,97,76,13,27, 49,55,65], exchange

arr = [38,04,49,97,76,13,27,49,55,65], visit in sequence until the sorting is completed

Code:

def bubble_sort(lists):  
    #冒泡排序  
    count = len(lists)  
    while count > 0:  
        for i in range(count - 1):  #最后一位数不进行比较  
            key = lists[i+1]  
            if lists[i] > key:  
                lists[i], lists[i+1] = key, lists[i]  
        count -= 1  
    return lists


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