python排序算法
1、冒泡排序:
import math
def BubbleSort(list):
lengthOfList = len(list)
for i in range(0,lengthOfList-1):
for j in xrange(i+1,lengthOfList):
if list[i]>list[j]:
temp = list[i]
list[i] = list[j]
list[j] = temp
bList = [1,12,2,4,51,66,45,25,96,78,55,23]
print bList
BubbleSort(bList)
print bList
2、插入排序:
import math
def InsertSort(list):
lengthOfList = len(list)
for i in range(1,lengthOfList):
cur = list[i]
temp = i
while i>0 and list[temp - 1]>cur:
list[temp] = list[temp-1]
temp = temp -1
list[temp] = cur
bList = [1,12,2,4,51,66,45,25,96,78,55,23]
print bList
InsertSort(bList)
print bList
3、选择排序:
import math
def SelectSort(list):
lengthOfList = len(list)
for i in range(0,lengthOfList-1):
pos = i
for j in range(i + 1,lengthOfList):
if list[j]<list[pos]:
pos = j
if pos != i:
temp = list[i]
list[i] = list[pos]
list[pos] = temp
bList = [1,12,2,5,51,66,45,25,96,78,55,23]
print bList
SelectSort(bList)
print bList
4、快速排序算法:
#快速排序的原理是将取出第一个数,将整个数组分为两波,一拨都大于这个数,另一波都小于这个数,
#然后递归用同样的方法处理第一波数字和第二波数字。
import math
def QuickSort(list):
low = 0
high = len(list) - 1
if low < high:
s, i, j = list[low], low, high
while i < j:
while i < j and list[j] >= s:
j = j - 1
if i < j:
list[i] = list[j]
i = i + 1
while i < j and list[i] <= s:
i = i + 1
if i < j:
list[j] = list[i]
j = j - 1
list[i] = s
QuickSort(list, low, i - 1)
QuickSort(list, i + 1, high)
bList = [1,12,2,5,51,66,45,25,96,78,55,23]
print bList
QuickSort(bList,0,11)
print bLis