本文参考老男孩视屏
算法
一个计算过程,解决问题的方法
输入-->算法-->输出
递归
- 调用自身
- 结束条件
时间复杂度
O(1)
print('hello word')
O(n2)
for i in range(n):
for l in range(n):
O(n3)
for i in range(n):
for l in range(n):
for k in range(n):
O(logn)
while n>0:
n//2
总结
时间复杂用来估计一个算法运行式子
O(1)<O(logn)<O(n)<O(nlogn)<O(n2)<O(n2logn)<O(n3)
空间复杂度
列表查找
顺序查找 O(n)
def linear_search(data_set, value):
for i in range(range(data_set)):
if data_set[i] == value:
return i
return
二分查找 (logn)
def bin_search(data_set,val):
low = 0
high =len(data_set) - 1
while low <= high:
mid = (low+high)//2
if data_set[mid] == val:
return mid
elif data_set[mid] <val:
low =mid +1
else:
high = mid-1
return
bin_search()
排序:
冒泡排序(bubble_sort)
选个开始一个数,通过交换把一个大的数选出来,便利一趟可以选出一个最大的数据,
import random,time
def func_time(func):
def wapper(*args,**kwargs):
time_start =time.time()
x = func(*args,**kwargs)
time_stop = time.time() -time_start
print("time cost:",time_stop)
return x
return wapper
@func_time
def bubble_sort(li):
for i in range(len(li) - 1):
exchange = False
for k in range(len(li) - i - 1):
if li[k] > li[k+1]:
li[k],li[k+1] = li[k+1],li[k]
exchange = True
if not exchange:
break
data = list(range(10000))
random.shuffle(data)
bubble_sort(data)
print(data)