更新時(shí)間:2021-03-24 來(lái)源:黑馬程序員 瀏覽量:
python 冒泡排序?qū)崿F(xiàn)方法
def bubble_sort(lists): count = len(lists) for i in range(0, count): for j in range(i + 1, count): if lists[i] > lists[j]: #判斷后值是否比前置大,如果大就將其交換 lists[i], lists[j] = lists[j], lists[i] return lists res=bubble_sort([1,209,31,4,555,6,765,9,5,4,7,89,6,5,34,3,57,96]) print(res)
python 遞歸排序
def merge_sort(li): n = len(li) if n == 1: return li # 把數(shù)據(jù)分成左右兩部分 mid = n // 2 left = li[:mid] right = li[mid:] # 遞歸拆分 left_res = merge_sort(left) right_res = merge_sort(right) # 把下層返回上來(lái)的數(shù)據(jù),組成有序序列 result = merge(left_res, right_res) # 合并 return result def merge(left, right): result = [] left_index = 0 right_index = 0 while left_index < len(left) and right_index < len(right): if left[left_index] <= right[right_index]: result.append(left[left_index]) left_index += 1 else: result.append(right[right_index]) right_index += 1 # while循環(huán)結(jié)束后,把剩下的數(shù)據(jù)添加進(jìn)來(lái) result += right[right_index:] result += left[left_index:] return result if __name__ == '__main__': list_demo = [6, 5, 7, 4, 3, 1] print(merge_sort(list_demo))
python 選擇排序
def select_sort(lists): # 選擇排序 count = len(lists) for i in range(0, count): min = i for j in range(i + 1, count): if lists[min] > lists[j]: min = j lists[min], lists[i] = lists[i], lists[min] return lists res=select_sort([1,209,31,4,555,6,765,9,5,4,7,89,6,5,34,3,57,96]) print(res)
猜你喜歡:
長(zhǎng)沙python培訓(xùn)哪個(gè)培訓(xùn)機(jī)構(gòu)比較好?【資源福利】python全套視頻教程下載
2021-03-23Python爬蟲(chóng)難學(xué)嗎?學(xué)會(huì)需要多久?
2021-03-23python培訓(xùn)哪家比較靠譜?【資源福利】python教程入門(mén)到精通下載
2021-03-19重慶python培訓(xùn)哪個(gè)培訓(xùn)班好?|資源福利|Python基礎(chǔ)教程下載
2021-03-19python培訓(xùn)機(jī)構(gòu)哪里好?百度云資源python基礎(chǔ)教程百度云資源
2021-03-19Python中的函數(shù)是什么?
2021-03-19