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

用Python实现几种排序算法

时间:2015-01-02 01:06:51      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

#coding=utf-8
# 1 快速排序算法
def qksort(list):
    if len(list)<=1:
        return list
    else:
        pivot = list[0]
        less=[x for x in list[1:] if x<pivot]
        greater=[y for y in list[1:] if y>=pivot]
        return qksort(less)+[pivot]+qksort(greater)
    

q=[1,3,8,3,2,6,5,3,5,7]
t=qksort(q)
print (t)

#coding=utf-8
# 2 插入排序算法
def insection_sort(list):
    n=len(list)
    for index in range(1,n):
        j=index-1
        value=list[index]
        while j>=0:
            if value<list[j]:
                list[j+1]=list[j]
                list[j]=value
            else :
                break
            j=j-1
    return list

q=[1,3,8,3,2,6,5,3,5,7]
t=insection_sort(q)
print (t)  

#coding=utf-8
# 3 冒泡排序算法
def bubble_sort(list):
    n=len(list)
    for i in range (n):
        for j in range(i+1,n):
            if list[j]<list[i]:
                temp=list[j]
                list[j]=list[i]
                list[i]=temp
    return list

q=[1,3,8,3,2,6,5,3,5,7]
t=bubble_sort(q)
print (t)  

 

用Python实现几种排序算法

标签:

原文地址:http://www.cnblogs.com/lizhaoxian/p/4197984.html

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