首页 > 编程语言 > 详细

Python 排序算法的实现

时间:2014-08-06 22:23:07      阅读:411      评论:0      收藏:0      [点我收藏+]

冒泡排序:

1 def bubble(l):
2     length = len(l)
3     for i in range(length):
4         for j in range(i+1, length):
5             if l[i] > l[j]:
6                 l[i], l[j] = l[j], l[i]
7     print l

选择排序:

1 def select(l):
2     length = len(l)
3     for i in range(length):
4         minn = i
5         for j in range(i+1, length):
6             if l[j] < l[minn]:
7                 minn = j
8         l[i], l[minn] = l[minn], l[i]
9     print l

插入排序:

 1 def insert(l):
 2     length = len(l)
 3     for i in range(1,length):
 4         key = l[i]
 5         j = i - 1
 6         while j > 0 and l[j] > key:
 7             l[j+1] = l[j]
 8             j -= 1
 9         l[j+1] = key
10     print l

快速排序:

(1)传统版

 1 def quick(l, left, right):
 2     if left < right:
 3         pivot = partition(l, left, right)
 4         quick(l, left, pivot - 1)
 5         quick(l, pivot + 1, right)
 6 
 7 
 8 def partition(l, left, right):
 9     pivot = l[left]
10     i, j = left, right
11     while i < j:
12         while i < j and l[j] >= pivot:
13             j -= 1
14         if i < j:
15             l[i] = l[j]
16             i += 1
17         while i < j and l[i] <= pivot:
18             i += 1
19         if i < j:
20             l[j] = l[i]
21             j -= 1
22     l[i] = pivot
23     return i

(2)简易版

1 def quick_simple(l):
2     if len(l) > 1:
3         return quick_simple( [i for i in l[1:] if i < l[0]] ) + l[0:1] + quick_simple( [j for j in l[1:] if j >= l[0]] )
4     else:
5         return l

未完待续...

Python 排序算法的实现,布布扣,bubuko.com

Python 排序算法的实现

原文:http://www.cnblogs.com/ethanchou/p/3895584.html

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