①冒泡排序
def my_change(a, b):
if a > b:
return b, a
else:
return a, b
src_lst = [1, 3, 2, 10, 6, 9, 5]
for i in range(len(src_lst)-1):
for j in range(len(src_lst)-i-1):
src_lst[j], src_lst[j+1] = my_change(src_lst[j], src_lst[j+1])
print src_lst
②二分查找
dest_number = 1
src_lst = [1, 3, 2, 10, 6, 9, 5]
src_lst.sort()
n = len(src_lst)
left = 0
right = n-1
while left <= right:
meight = (left+right) / 2
if src_lst[meight] > dest_number:
right = meight-1
elif src_lst[meight] < dest_number:
left = left+1
else:
print '目的对象在列表中的下标为:'
print src_lst.index(src_lst[meight])
break
else:
print 'not found'
③堆排
src_lst = [1,3,2,10,6,9,5]
for i in range(len(src_lst)):
j = i
while j > 0:
if src_lst[j] < src_lst[(j-1)/2]:
break
src_lst[j], src_lst[(j-1)/2] = src_lst[(j-1)/2], src_lst[j]
j = (j-1)/2
print '形成堆:'
print src_lst
for i in range(len(src_lst)):
tmp_idx = len(src_lst)-i-1
src_lst[0], src_lst[tmp_idx] = src_lst[tmp_idx], src_lst[0]
j = 0
while 2*j+2 < tmp_idx:
max_idx = 2*j +1
if src_lst[2*j+2] > src_lst[2*j+1]:
max_idx = 2*j +2
if src_lst[j] > src_lst[max_idx]:
break
else:
src_lst[j], src_lst[max_idx] = src_lst[max_idx], src_lst[j]
if 2*j+1 < tmp_idx and src_lst[j] < src_lst[2*j+1]:
src_lst[j], src_lst[2*j+1] = src_lst[2*j+1], src_lst[j]
print '排序结果:'
print src_lst
④快速排序
src_lst = [1,3,2,10,6,9,5]
def fastSort(left, right):
if left >= right:
return
tmp = src_lst[left]
i = left
j = right
while i != j:
while src_lst[j] >= tmp and i < j:
j-=1
while src_lst[i] <= tmp and i < j:
i+=1
if i<j:
src_lst[i], src_lst[j] = src_lst[j], src_lst[i]
src_lst[left], src_lst[i] = src_lst[i], src_lst[left]
fastSort(left, i-1)
fastSort(i+1, right)
fastSort(0, len(src_lst)-1)
print src_lst
持续更新中...