算法入门
算法
算法
什么是算法
算法(Algorithm):一个计算过程,解决问题的方法
时间复杂度
print('Hello World') O(1) for i in range(n): O(n) print('Hello World') for i in range(n): O(n2) for j in range(n): print('Hello World') for i in range(n): O(n3) for j in range(n): for k in range(n): print('Hello World') while n > 1: O(logn) print(n) n = n // 2
二分查找法
def bin_search_rec(data_set, value, low, high): if low <= high: mid = (low + high) // 2 if data_set[mid] == value: return mid elif data_set[mid] > value: return bin_search_rec(data_set, value, low, mid - 1) else: return bin_search_rec(data_set, value, mid + 1, high) else: return
排序算法
冒泡排序法
def bubble_sort_1(li): for i in range(len(li)-1): exchange = False for j in range(len(li)-i-1): if li[j] > li[j+1]: li[j], li[j+1] = li[j+1], li[j] exchange = True if not exchange: return
选择排序
def select_sort(li): for i in range(len(li) - 1): min_loc = i for j in range(i+1, len(li)): if li[j] < li[min_loc]: min_loc = j if min_loc != i: li[i], li[min_loc] = li[min_loc], li[i]
插入排序
def insert_sort(li): for i in range(1, len(li)): tmp = li[i] j = i - 1 while j >= 0 and tmp < li[j]: li[j + 1] = li[j] j = j - 1 li[j + 1] = tmp
快速排序
def quick_sort(data, left, right): if left < right: mid = partition(data, left, right) quick_sort(data, left, mid - 1) quick_sort(data, mid + 1, right) def partition(data, left, right): tmp = data[left] while left < right: while left < right and data[right] >= tmp: right -= 1 data[left] = data[right] while left < right and data[left] <= tmp: left += 1 data[right] = data[left] data[left] = tmp return left
归并排序
def mergesort(li, low, high): if low < high: mid = (low + high) // 2 mergesort(li, low, mid) mergesort(li, mid + 1, high) merge(li, low, mid, high) def merge(li, low, mid, high): i = low j = mid + 1 ltmp = [] while i <= mid and j <= high: if li[i] <= li[j]: ltmp.append(li[i]) i += 1 else: ltmp.append(li[j]) j += 1 while i <= mid: ltmp.append(li[i]) i += 1 while j <= high: ltmp.append(li[j]) j += 1 li[low:high + 1] = ltmp
希尔排序
def shell_sort(li): gap = len(li) // 2 while gap > 0: for i in range(gap, len(li)): tmp = li[i] j = i - gap while j >= 0 and tmp < li[j]: li[j + gap] = li[j] j -= gap li[j + gap] = tmp gap /= 2
计数排序
def count_sort(li, max_num): count = [0 for i in range(max_num + 1)] for num in li: count[num] += 1 i = 0 for num,m in enumerate(count): for j in range(m): li[i] = num i += 1