当前位置:网站首页>1: bubble sort

1: bubble sort

2022-08-09 09:59:00 User 9955628

Idea: Compare two adjacent elements in turn, the smaller ones are in the front, the larger ones are in the back, and if the order is wrong, the order of the two is swapped.

range function:

range(start,stop,[step]): Generate aiterate objectbe careful:setp can be omitted, the default is 1Left closed right open intervalExample:range(10) # start from 0 to 10[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]range(0, 30, 5) # steps are 5[0, 5, 10, 15, 20, 25]range(0, 10, 3) # steps are 3[0, 3, 6, 9]range(0, -10, -1) # negative numbers[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]range(0)[]range(1, 0)[]

python3 implementation:

from typing import Listdef bubble_sort(arr: List[int]):"""arr: the list to be sorted, the element type in the list is int"""length = len(arr)#Return directly when the list length is 1 and 0if length <= 1:returnfor i in range(length-1):is_made_swap = False#Set the flag bit, if it is already in order, jump out directlyfor j in range(length-1):if arr[j] > arr[j+1]:arr[j],arr[j+1] = arr[j+1],arr[j]is_made_swap = Trueif not is_made_swap:breakif __name__ == '__main__':import randomrandom.seed(54)arr = [random.randint(0,100) for _ in range(10)]print("raw data", arr)bubble_sort(arr)print("After sorting: ",arr)result:Raw data [17, 56, 71, 38, 61, 62, 48, 28, 57, 42]After sorting: [17, 28, 38, 42, 48, 56, 57, 61, 62, 71]
原网站

版权声明
本文为[User 9955628]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208090943259167.html