各种排序算法-用Python实现
冒泡排序
# 冒泡排序
def bubble_sort(l):
length = len(l)
# 外层循环 length遍,内层循环少一遍
while length:
for j in range(length - 1):
# 找出最大值,然后交换位置到最后
if l[j] > l[length - 1]:
l[j], l[length - 1] = l[length - 1], l[j]
length -= 1
if __name__ == "__main__":
l = [5, 1, 9, 3, 2, 7]
bubble_sort(l)
print l
插入排序
"""
插入排序和冒泡排序的区别在于:
插入排序的前提是:左边是有序的数列
而冒泡排序:相邻的值进行交换,一共进行n次交换
"""
def insert_sort(l):
# 循环 除第一个数字组成的有序数组 以外的数字
for i in range(1, len(l)):
# 每一个数字,依次和有序数组进行比较
print l[:i]
for j in range(len(l[:i])):
if l[i] < l[j]:
l[i], l[j] = l[j], l[i]
if __name__ == "__main__":
l = [5, 1, 9, 3, 2, 7]
print l
insert_sort(l)
print("result: " + str(l))
归并排序
def MergeSort(lists):
if len(lists) <= 1:
return lists
num = int(len(lists) / 2)
# 从中间,进行数据的拆分, 递归的返回数据进行迭代排序
left = MergeSort(lists[:num])
right = MergeSort(lists[num:])
print left
print "*" * 20
print right
print "_" * 20
return Merge(left, right)
def Merge(left, right):
r, l = 0, 0
result = []
while l < len(left) and r < len(right):
if left[l] < right[r]:
result.append(left[l])
l += 1
else:
result.append(right[r])
r += 1
result += right[r:]
result += left[l:]
print 'result:', result
return result
if __name__ == "__main__":
print MergeSort([1, 2, 3, 4, 5, 6, 7, 90, 21, 23, 45])
快速排序
def quick_sort(l, start, end):
i = start
j = end
# 结束排序
if i >= j:
return
# 保存首个数值
key = l[i]
# 一次排序,i和j的值不断的靠拢,然后最终停止,结束一次排序
while i < j:
# 和最右边的比较,如果>=key,然后j-1,慢慢的和前一个值比较;如果值<key,那么就交换位置
while i < j and key <= l[j]:
print key, l[j], '*' * 30
j -= 1
l[i] = l[j]
# 交换位置后,然后在和最左边的值开始比较,如果<=key,然后i+1,慢慢的和后一个值比较;如果值>key,那么就交换位置
while i < j and key >= l[i]:
print key, l[i], '*' * 30
i += 1
l[j] = l[i]
l[i] = key
# 左边排序
quick_sort(l, start, j-1)
# 右边排序
quick_sort(l, i+1, end)
if __name__ == "__main__":
l = [5, 1, 9, 3, 2, 7]
quick_sort(l, 0, len(l) - 1)
print l
选择排序
"""
选择排序和冒泡排序的区别在于:
选择排序的前提是:找到最大值的位置,最后才进行1次交换
而冒泡排序:相邻的值进行交换,一共进行n次交换
"""
def selection_sort(l):
length = len(l) - 1
while length:
index = length
# 第一个数字,和后面每一个数字进行对比,找出最大值,放到最后!!
for j in range(length):
if l[j] > l[index]:
index = j
l[length], l[index] = l[index], l[length]
print len(l) - length, l
length -= 1
if __name__ == "__main__":
l = [5, 1, 9, 3, 2, 7]
print l
selection_sort(l)
print("result: " + str(l))
希尔排序
def insert_sort(l, start, increment):
for i in range(start+increment, len(l), increment):
for j in range(start, len(l[:i]), increment):
if l[i] < l[j]:
l[i], l[j] = l[j], l[i]
print increment, '--',l
return l
def shell_sort(l, increment):
# 依次进行分层
while increment:
# 每一层,都进行n次插入排序
for i in range(0, increment):
insert_sort(l, i, increment)
increment -= 1
return l
if __name__ == "__main__":
l = [5, 2, 9, 8, 1, 10, 3, 4, 7]
increment = len(l)/3+1 if len(l)%3 else len(l)/3
print "开始", l
l = shell_sort(l, increment)
print "结束", l
树递归
class Node():
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def midRecusion(node):
if node is None:
return
midRecusion(node.left)
print node.value,
midRecusion(node.right)
def midIterator(node):
stack = []
while stack or node:
if node is not None:
stack.append(node)
node = node.left
else:
node = stack.pop(-1)
print node.value,
node = node.right
if __name__ == "__main__":
node = Node("D", Node("B", Node("A"), Node("C")), Node("E", right=Node("G", left=Node("F"))))
print('\n中序遍历<递归>:')
midRecusion(node)
print('\n中序遍历<迭代>:')
midIterator(node)
更新冒泡排序
'''
迭代使用的是循环结构。
递归使用的是选择结构。
'''
# 递归求解
def calculate(l):
if len(l) <= 1:
return l[0]
value = calculate(l[1:])
return 10**(len(l) - 1) * l[0] + value
# 迭代求解
def calculate2(l):
result = 0
while len(l) >= 1:
result += 10 ** (len(l)-1) * l[0]
l = l[1:]
return result
l1 = [1, 2, 3]
l2 = [4, 5]
sum = 0
result = calculate(l1) + calculate(l2)
# result = calculate2(l1) + calculate2(l2)
print(result)
本文版权归作者和博客园共有,欢迎转载,转载请注明出处和链接来源。