deflinearithmic_algo(items): iflen(items) > 1: mid = len(items) // 2 left = items[:mid] right = items[mid:]
linearithmic_algo(left) linearithmic_algo(right)
i = 0 j = 0 k = 0
while i < len(left) and j < len(right): if left[i] < right[j]: items[k] = left[i] i += 1 else: items[k] = right[j] j += 1 k += 1
while i < len(left): items[k] = left[i] i += 1 k += 1
while j < len(right): items[k]=right[j] j += 1 k += 1
O(2^n):指數時間
1 2 3 4 5 6 7 8 9
defexponential_algo(items): iflen(items)==0: return [[]] smaller = exponential_algo(items[:-1]) extra = items[-1:] new = [] for small in smaller: new.append(small+extra) return smaller+new
O(n!):階乘時間
1 2 3 4 5 6 7 8 9
deffactorial_algo(items): iflen(items)==0: return [[]] smaller = factorial_algo(items[:-1]) new = [] for small in smaller: for i inrange(0,len(small)+1): new.append(small[:i]+items[-1:]+small[i:]) return smaller+new
O(n^n):階乘時間
1 2 3 4 5 6 7 8 9
defn_power_n_algo(items): iflen(items)==0: return [[]] smaller = n_power_n_algo(items[:-1]) new = [] for small in smaller: for i inrange(0,len(small)+1): new.append(small[:i]+items[-1:]+small[i:]) return smaller+new
O(n^3):立方時間
1 2 3 4 5
defcubic_algo(items): for item in items: for item2 in items: for item3 in items: print(item, ' ', item2, ' ', item3)