Home >Backend Development >Python Tutorial >Use python to implement 8 sorting algorithms-bubble sort
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