首页 > 编程语言 > 详细

Python三种排序算法

时间:2017-08-06 23:38:59      阅读:173      评论:0      收藏:0      [点我收藏+]

冒泡排序:

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三种排序算法

原文:http://www.cnblogs.com/lzh1118/p/7296248.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!