码迷,mamicode.com
首页 > 编程语言 > 详细

Python三种排序算法

时间:2017-08-07 00:12:56      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:排序算法   lis   交换   div   冒泡   sel   key   list   ret   

冒泡排序:

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

标签:排序算法   lis   交换   div   冒泡   sel   key   list   ret   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!