文章目录
- 各种算法
- 选择排序
- 插入排序
- 希尔排序
- ***快速排序***
- 归并排序
- 二分查找
各种算法
def bubble_sort(alist):"""冒泡排序"""n = len(alist)for j in range(n-1):count = 0for i in range(0, n-1-j):# 班长从头走到尾if alist[i] > alist[i+1]:alist[i],alist[i+1] = alist[i+1], alist[i]count += 1if 0 == count:return
选择排序
def select_sort(alist):"""选择排序"""n = len(alist)for j in range(n-1): # j: 0 ~ n-2min_index = jfor i in range(j+1, n):if alist[min_index] > alist[i]:min_index = ialist[j], alist[min_index] = alist[min_index], alist[j]
插入排序
def insert_sort(alist):"""插入排序"""n = len(alist)# 从右边的无序序列中取出多少个元素执行这样的过程for j in range(1, n):# j = [1, 2, 3, n-1]# i 代表内层循环起始值i = j# 执行从右边的无序序列中取出第一个元素,即i位置的元素,然后将其插入到前面的正确位置中while i > 0:if alist[i] < alist[i-1]:alist[i], alist[i-1] = alist[i-1], alist[i]i -= 1else:break
希尔排序
ef shell_sort(alist):"""希尔排序"""# n=9n = len(alist)# gap =4gap = n // 2# i = gap# for i in range(gap, n):# # i = [gap, gap+1, gap+2, gap+3... n-1]# while:# if alist[i] < alist[i-gap]:# alist[i], alist[i-gap] = alist[i-gap], alist[i]# gap变化到0之前,插入算法执行的次数while gap > 0:# 插入算法,与普通的插入算法的区别就是gap步长for j in range(gap, n):# j = [gap, gap+1, gap+2, gap+3, ..., n-1]i = jwhile i > 0:if alist[i] < alist[i-gap]:alist[i], alist[i-gap] = alist[i-gap], alist[i]i -= gapelse:break# 缩短gap步长gap //= 2
快速排序
def quick_sort(alist, first, last):"""快速排序"""if first >= last:returnmid_value = alist[first]low = firsthigh = lastwhile low < high:# high 左移while low < high and alist[high] >= mid_value:high -= 1alist[low] = alist[high]while low <high and alist[low] < mid_value:low += 1alist[high] = alist[low]# 从循环退出时,low==highalist[low] = mid_value# 对low左边的列表执行快速排序quick_sort(alist, first, low-1)# 对low右边的列表排序quick_sort(alist, low+1, last)
归并排序
def merge_sort(alist):"""归并排序"""n = len(alist)if n <= 1:return alistmid = n//2# left 采用归并排序后形成的有序的新的列表left_li = merge_sort(alist[:mid])# right 采用归并排序后形成的有序的新的列表right_li = merge_sort(alist[mid:])# 将两个有序的子序列合并为一个新的整体# merge(left, right)left_pointer, right_pointer = 0, 0result = []while left_pointer < len(left_li) and right_pointer < len(right_li):if left_li[left_pointer] <= right_li[right_pointer]:result.append(left_li[left_pointer])left_pointer += 1else:result.append(right_li[right_pointer])right_pointer += 1result += left_li[left_pointer:]result += right_li[right_pointer:]return result
二分查找
def binary_search(alist, item):"""二分查找,递归"""n = len(alist)if n > 0:mid = n//2if alist[mid] == item:return Trueelif item < alist[mid]:return binary_search(alist[:mid], item)else:return binary_search(alist[mid+1:], item)return Falsedef binary_search_2(alist, item):"""二分查找, 非递归"""n = len(alist)first = 0last = n-1while first <= last:mid = (first + last)//2if alist[mid] == item:return Trueelif item < alist[mid]:last = mid - 1else:first = mid + 1return False