Sorting Algorithm (5)---Bubble Sort (Exchange Sort)

Bubble sort belongs to exchange sort.

Basic idea:
  In the sequence to be sorted, compare and adjust two adjacent elements from top to bottom, small ones rise up, and large ones sink

. Time complexity:
  best case: positive order Ordered, only need to compare n times, O(n)
  worst case: reverse order ordered, need to compare (n-1)+(n-2)+...1 times, so O(n*n) is

stable Performance : Stable

Code Example: bubble_sort.py
def bubble_sort(l):
    length = len(l)
    for i in range(0, length):
        for j in range(0, length-i-1):
            if l[j] > l[j+1]:
                tmp = l[j]
                l[j] = l[j+1]
                l[j+1] = tmp

if __name__ == '__main__':
    l = [52,13,65,21,18,72,43,39,58,9]
    bubble_sort(l)
    print('result:'+ str(l))

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326592858&siteId=291194637