Python三种排序算法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python三种排序算法相关的知识,希望对你有一定的参考价值。
冒泡排序:
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)
快速排序:
def quick_sort(lists, left, right): # 快速排序 if left >= right: return lists key = lists[left] low = left high = right while left < right: while left < right and lists[right] >= key: right -= 1 lists[left] = lists[right] while left < right and lists[left] <= key: left += 1 lists[right] = lists[left] lists[right] = key quick_sort(lists, low, left - 1) quick_sort(lists, left + 1, high) return lists
选择排序:
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 print("--------",lists[min], lists[i]) lists[min], lists[i] = lists[i], lists[min] print(lists[min], lists[i]) 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)
以上是关于Python三种排序算法的主要内容,如果未能解决你的问题,请参考以下文章