數據結構:
計算機存儲,組織數據的結構。指相互之間存在着一種或多種關係的數據元素的集合和該集合中數據元素之間的關係組成.
線性數據結構:數組,鏈表 應用:隊列 棧
非線性數據結構:樹,圖
算法:
對數據結構中數據的操做
low B三件套算法
#冒泡排序 #時間複雜度:O(n2) #空間複雜度:O(1) def bubble_sort(li): for i in range(len(li)-1): flag = False for j in range(len(li)-i-1): if li[j+1] < li[j]: li[j+1], li[j] = li[j], li[j+1] flag = True if not flag: return
# 選擇排序 # 時間複雜度: O(n^2) # 空間複雜度: O(1) def select_sort(li): for i in range(len(li)-1): minLoc = i for j in range(i+1,len(li)): if li[j] < li[minLoc]: # li[2] < li[0] li[j], li[minLoc] = li[minLoc], li[j]
# 插入排序 # 時間複雜度: O(n^2) # 空間複雜度: O(1) 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
N B三件套數組
# 快速排序 # 時間複雜度: O(nlogn) # 空間複雜度: O(1) def patition(li, left, right): tmp = li[left] # 5 while left < right: while left < right and tmp <= li[right]: right = right - 1 li[left] = li[right] # [2,7,4,6,3,1,2,9,8] # [2,1,4,6,3,1,2,9,8] while left < right and tmp >= li[left]: left = left + 1 li[right] = li[left] # [2,7,4,6,3,1,7,9,8] li[left] = tmp return left def quick_sort(li, left, right): if left < right: mid = patition(li, left, right) quick_sort(li, left, mid-1) quick_sort(li, mid+1, right)
# 歸併算法 # 時間複雜度: O(nlogn) # 空間複雜度: O(n) def merge(li, left, mid, right): i = left j = mid + 1 ltmp = [] while i <= mid and j <= right: if li[i] < li[j]: ltmp.append(li[i]) i = i + 1 else: ltmp.append(li[j]) j = j + 1 while i <= mid: ltmp.append(li[i]) i = i + 1 while j <= right: ltmp.append(li[j]) j = j + 1 li[left:right+1] = ltmp def merge_sort(li, left, right): if left < right: mid = (left + right) // 2 merge_sort(li, left, mid) merge_sort(li, mid+1, right) merge(li, left, mid, right)