上课讲解代码
binary tree的实现
class Node(object):
def __init__(self,item):
self.item=item
self.left=None
self.right=None
class binaryTree(object):
def __init__(self):
self.root=None #首先定义一个根节点
def add(self,item):
node=Node(item) #i将tem其转化为Node型
queue=[self.root] #用队列存储根节点
if self.root is None:
self.root=node #如果根节点为空那么就将node赋值给根节点root
return
while queue: #只要队列不为空就执行while语句里面的内容
cur_node=queue.pop(0) # cur_node用于存储队列弹出的元素
if cur_node.left is None:
cur_node.left=node #判断左子树是否为空,为空则把node赋值给左子树
return
else:
queue.append(cur_node.left) #如果不是空,则把cur_node.的左孩子放入队列当中
if cur_node.right is None:
cur_node.right=node#判断左子树是否为空,为空则把node赋值给右子树
return
else:
queue.append(cur_node.right)
def breadth_travel(self):
"""层次遍历"""
if self.root is None:
return
queue=[self.root]
while queue:
cur_node=queue.pop(0)
print(cur_node.item,end=" ")
if cur_node.left is not None:
queue.append(cur_node.left)
if cur_node.right is not None:
queue.append(cur_node.right)
def preorder(self,root):
"""先序遍历"""
if root is None:
return
print(root.item,end=" ")
self.preorder(root.left)
self.preorder(root.right)
def inorder(self,root):
"""中序遍历"""
if root is None:
return
self.inorder(root.left)
print(root.item,end=" ")
self.inorder(root.right)
def afterorder(self,root):
"""后序遍历"""
if root is None:
return
self.afterorder(root.left)
self.afterorder(root.right)
print(root.item,end=" ")
tree=binaryTree()
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
tree.add(6)
tree.add(7)
tree.add(8)
tree.add(9)
print("层次遍历结果:")
tree.breadth_travel()
print("\n")
print("先序遍历结果:")
tree.preorder(tree.root)
print("\n")
print("中序遍历结果:")
tree.inorder(tree.root)
print("\n")
print("后序遍历结果:")
tree.afterorder(tree.root)
heap
class MaxHeap:
def __init__(self, maxSize):
self.__elements = [0] * maxSize
self.__count = 0
def __len__(self):
return self.__count
def capacity(self):
return len(self.__elements)
def add(self, value):
assert self.__count < self.capacity(), "Cannot add to full heap."
self.__elements[self.__count] = value
self.__count += 1
self.__sift_up(self.__count - 1)
def __sift_up(self, ndx):
if ndx > 0:
parent = (ndx - 1) // 2
if self.__element[ndx] > self.__elements[parent]:
self.__element[ndx], self.__elements[parent] = self.__elements[parent], self.__elements[ndx]
self.__sift_up(parent)
def extract(self):
assert self.__count > 0, "Cannot extract from the heap"
value = self.__elements[0]
self.__count -= 1
self.__element[0] = self.__elements[self.__count]
self.__sift_down(0)
return value
def __sift_down(self, ndx):
min_idx = ndx
if 2 * ndx <= self.__count and self.__elements[2 * ndx] < self.__elements[min_idx]:
min_idx = 2 * ndx
if 2 * ndx + 1 <= self.__count and self.__elements[2 * ndx + 1] < self.__elements[min_idx]:
min_idx = 2 * ndx + 1
if min_idx != ndx:
self.__element[ndx], self.__elements[min_idx] = self.__elements[min_idx], self.__elements[ndx]
self.__sift_down(min_idx)
冒泡排序
Bubblesort
def bubbleSort(arr):
n = len(arr)
# 遍历所有数组元素
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("排序后的数组:")
for i in range(len(arr)):
print ("%d" %arr[i])
选择排序
A = [64, 25, 12, 22, 11]
for i in range(len(A)):
min_idx = i
for j in range(i + 1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
print("排序后的数组:")
for i in range(len(A)):
print("%d" % A[i]),
快速排序
def quick_sort(arr, left, right):
if left >= right:
return
i = left - 1
j = right + 1
x = arr[(i+j)//2]
while left < right:
while True:
i += 1
if arr[i] >= x:
break
while True:
j -= 1
if arr[j] <= x:
break
if i < j:
arr[i], arr[j] = arr[j], arr[i]
else:
break
quick_sort(arr, left, j)
quick_sort(arr, j+1, right)
nums = [12,21,10,3,4,5]
n = len(nums)
quick_sort(nums, 0, n-1)
for i in nums:
print(i, end = ' ')
def quick_sort(alist, start, end):
"""快速排序"""
if start >= end: # 递归的退出条件
return
mid = alist[start] # 设定起始的基准元素
low = start # low为序列左边在开始位置的由左向右移动的游标
high = end # high为序列右边末尾位置的由右向左移动的游标
while low < high:
# 如果low与high未重合,high(右边)指向的元素大于等于基准元素,则high向左移动
while low < high and alist[high] >= mid:
high -= 1
alist[low] = alist[high] # 走到此位置时high指向一个比基准元素小的元素,将high指向的元素放到low的位置上,此时high指向的位置空着,接下来移动low找到符合条件的元素放在此处
# 如果low与high未重合,low指向的元素比基准元素小,则low向右移动
while low < high and alist[low] < mid:
low += 1
alist[high] = alist[low] # 此时low指向一个比基准元素大的元素,将low指向的元素放到high空着的位置上,此时low指向的位置空着,之后进行下一次循环,将high找到符合条件的元素填到此处
# 退出循环后,low与high重合,此时所指位置为基准元素的正确位置,左边的元素都比基准元素小,右边的元素都比基准元素大
alist[low] = mid # 将基准元素放到该位置,
# 对基准元素左边的子序列进行快速排序
quick_sort(alist, start, low - 1) # start :0 low -1 原基准元素靠左边一位
# 对基准元素右边的子序列进行快速排序
quick_sort(alist, low + 1, end) # low+1 : 原基准元素靠右一位 end: 最后
if __name__ == '__main__':
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
quick_sort(alist, 0, len(alist) - 1)
print(alist)
归并排序
def mergesort(seq):
"""归并排序"""
if len(seq) <= 1:
return seq
mid = len(seq) // 2 # 将列表分成更小的两个列表
# 分别对左右两个列表进行处理,分别返回两个排序好的列表
left = mergesort(seq[:mid])
right = mergesort(seq[mid:])
# 对排序好的两个列表合并,产生一个新的排序好的列表
return merge(left, right)
def merge(left, right):
"""合并两个已排序好的列表,产生一个新的已排序好的列表"""
result = [] # 新的已排序好的列表
i = 0 # 下标
j = 0
# 对两个列表中的元素 两两对比。
# 将最小的元素,放到result中,并对当前列表下标加1
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
seq = [5,3,0,6,1,4]
print('排序前:',seq)
result = mergesort(seq)
print('排序后:',result)