1.选择排序
算法:
对于一组关键字{K1,K2,…,Kn}, 首先从K1,K2,…,Kn中选择最小值,假如它是 Kz,则将Kz与 K1对换;
然后从K2,K3,… ,Kn中选择最小值 Kz,再将Kz与K2对换。
如此进行选择和调换n-2趟,第(n-1)趟,从Kn-1、Kn中选择最小值 Kz将Kz与Kn-1对换,最后剩下的就是该序列中的最大值,一个由小到大的有序序列就这样形成
动态视频:http://v.youku.com/v_show/id_XMjU4NTY5NTcy.html?from=y1.2-1-95.3.6-2.1-1-1-5-0
def selectSort(array):
for i in range(0, len(array)):
min = i
for j in range(i+1, len(array)):
if array[j] < array[min]:
min = j
array[i], array[min] = array[min], array[i] def getRandomList():
array = []
for i in range(1, 10000):
array.append(i)
random.shuffle(array) return array if __name__ == '__main__':
array = getRandomList()
t1 = datetime.datetime.now()
# bubble_sort(array)
#quickSort(array, 0, len(array)-1)
selectSort(array)
t2 = datetime.datetime.now()
print t2 - t1
########
0:00:15.805000
[Finished in 16.0s]
2 插入排序
http://v.youku.com/v_show/id_XMzMyODk3NjI4.html?from=s1.8-1-1.2
def insertSort(array):
if len(array)< 2:
return array
for i in range(0, len(array)):
key = array[i]
j = i-1
while j >= 0 and array[j] > key:
array[j+1] = array[j]
j-=1
array[j+1] = key def getRandomList():
array = []
for i in range(1, 10000):
array.append(i)
random.shuffle(array) return array if __name__ == '__main__':
array = getRandomList()
t1 = datetime.datetime.now()
# bubble_sort(array)
#quickSort(array, 0, len(array)-1)
# selectSort(array)
insertSort(array)
t2 = datetime.datetime.now()
print array
print t2 - t1 ########
0:00:05.125000
[Finished in 5.6s]