pyrebot

Better not to ignore the past but learn from it instead. Otherwise, history has a way of repeating itself.

博客园 首页 新随笔 联系 订阅 管理

python排序算法

1、冒泡排序:

 1 import math
 2 def BubbleSort(list):
 3     lengthOfList = len(list)
 4     for i in range(0,lengthOfList-1):
 5         for j in xrange(i+1,lengthOfList):
 6             if list[i]>list[j]:
 7                 temp = list[i]
 8                 list[i] = list[j]
 9                 list[j] = temp
10 bList = [1,12,2,4,51,66,45,25,96,78,55,23]
11 print bList
12 BubbleSort(bList)
13 print bList                

 

2、插入排序:

 1 import math
 2 def InsertSort(list):
 3 lengthOfList = len(list)
 4 for i in range(1,lengthOfList):
 5   cur = list[i]
 6   temp = i
 7   while i>0 and list[temp - 1]>cur:
 8     list[temp] = list[temp-1]
 9     temp = temp -1
10     list[temp] = cur
11 bList = [1,12,2,4,51,66,45,25,96,78,55,23]
12 print bList
13 InsertSort(bList)
14 print bList

 

3、选择排序:

 1 import math
 2 def SelectSort(list):
 3 lengthOfList = len(list)
 4 for i in range(0,lengthOfList-1):
 5   pos = i
 6   for j in range(i + 1,lengthOfList):
 7     if list[j]<list[pos]:
 8       pos = j
 9   if pos != i:
10     temp = list[i]
11     list[i] = list[pos]
12     list[pos] = temp
13 bList = [1,12,2,5,51,66,45,25,96,78,55,23]
14 print bList
15 SelectSort(bList)
16 print bList

 

4、快速排序算法:

 1 #快速排序的原理是将取出第一个数,将整个数组分为两波,一拨都大于这个数,另一波都小于这个数,
 2 #然后递归用同样的方法处理第一波数字和第二波数字。
 3 import math
 4 def QuickSort(list):
 5     low = 0
 6     high = len(list) - 1
 7     if low < high:
 8        s, i, j = list[low], low, high
 9         while i < j:
10             while i < j and list[j] >= s:
11                 j = j - 1
12             if i < j:
13                 list[i] = list[j]
14                 i = i + 1
15             while i < j and list[i] <= s:
16                 i = i + 1
17             if i < j:
18                 list[j] = list[i]
19                j = j - 1
20           list[i] = s
21           QuickSort(list, low, i - 1)
22           QuickSort(list, i + 1, high)
23 bList = [1,12,2,5,51,66,45,25,96,78,55,23]
24 print bList
25 QuickSort(bList,0,11)
26 print bLis        

 

posted on 2013-11-11 18:03  pyrebot  阅读(155)  评论(0编辑  收藏  举报