1.冒泡演算法
list = [1, 5, 2, 6, 9, 3, 4, 0] print(len(list)) # 8 conunt = 1 while conunt < len(list): for i in range(len(list) - conunt): if list[i + 1] <= list[i]: list[i], list[i+1] = list[i+1], list[i] conunt += 1 print(list)
2.二分查找法
# 二分法查找一個數在不在串列中 lst = [11, 22, 33, 44, 55, 66, 77, 88] # 方法一回圈 n = 33 left = 0 right = len(lst) - 1 count = 1 while left <= right: middle = (left + right) // 2 if n < lst[middle]: right = middle - 1 elif n > lst[middle]: left = middle + 1 else: print("%s在串列中的下標是%d查找次數%d" % (n, middle, count)) break count += 1 else: print("%s不在串列lst中" % n) # 方法二尾遞回 def binary_search(n,left=0, right=len(lst)-1, count1=1): middle = (left + right) // 2 # count1 += 1 if left <= right: if n < lst[middle]: right = middle - 1 elif n > lst[middle]: left = middle + 1 else: return "%s在串列中的下標是%d查找次數%d" % (n, middle, count1) return binary_search(n,left, right, count1+1) return "%s不在串列lst中" % n res = binary_search(44) print(res) # 方法三切片+尾遞回 def binary_search(n, lst): left = 0 right = len(lst) - 1 if left > right: return "%s不在串列lst中" % n middle = (left + right) // 2 if n < lst[middle]: lst = lst[:middle] elif n > lst[middle]: lst = lst[middle+1:] else: return "%s在串列中" % n return binary_search(n, lst) res = binary_search(11, lst) print(res)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/47293.html
標籤:Python
下一篇:python 自動化專案在 Jenkins 構建時報 Finished: FAILURE 和 'python' 不是內部或外部命令 的錯誤解決辦法
