時(shí)間復(fù)雜度所耗費(fèi)的時(shí)間從小到大依次是
O(1)< O(logn) < O(n) < O(n*logn) < O(n^2) < O(n^3) < O(2^n) < O(n!) < O(n^n)
斐波那契數(shù)列
# encoding=utf-8
def fun(n):
a, b = 0, 1
while a < n:
print(a)
a, b = b, a+b
if __name__ == '__main__':
fun(1000)
冒泡排序
時(shí)間復(fù)雜度O(n^2)
# encoding=utf-8
def bubble_sort(data_list):
for i in range(len(data_list)-1): # i代表需要冒泡循環(huán)比較的次數(shù)
for j in range(len(data_list)-i-1): # j代表循環(huán)到的下標(biāo)位置
if data_list[j] > data_list[j+1]: # 判斷相鄰大小修肠,并進(jìn)行交換
data_list[j], data_list[j+1] = data_list[j+1], data_list[j]
return data_list
if __name__ == '__main__':
a = [10, 17, 50, 7, 30, 24, 27, 45, 15, 5, 36, 21]
data = bubble_sort(a)
print(data)
選擇排序
時(shí)間復(fù)雜度O(n^2)
# encoding=utf-8
def select_sort(data_list):
for i in range(len(data_list)-1):
min_index = i
for j in range(i+1, len(data_list)):
if data_list[j] < data_list[min_index]:
min_index = j
if min_index != i:
data_list[i], data_list[min_index] = data_list[min_index], data_list[i]
return data_list
if __name__ == '__main__':
a = [10, 17, 50, 7, 30, 24, 27, 45, 15, 5, 36, 21]
data = select_sort(a)
print(data)
插入排序
時(shí)間復(fù)雜度O(n^2)
# encoding=utf-8
def insert_sort(data_list):
for i in range(1, len(data_list)):
for j in range(i, 0, -1):
if data_list[j] > data_list[j-1]:
data_list[j], data_list[j-1] = data_list[j-1], data_list[j]
return data_list
if __name__ == '__main__':
a = [10, 17, 50, 7, 30, 24, 27, 45, 15, 5, 36, 21]
data = insert_sort(a)
print(data)
快速排序
# encoding=utf-8
def quick_sort(data_list, start, end):
"""
快速排序
:param data_list: 未排序的list
:param start: 起始元素下標(biāo)
:param end: 結(jié)束元素下標(biāo)
:return: 排序后的list
"""
if start >= end:
return
mid = data_list[start]
low = start
high = end
while low < high:
while low < high and data_list[high] >= mid:
high -= 1
data_list[low] = data_list[high]
while low < high and data_list[low] < mid:
low += 1
data_list[high] = data_list[low]
data_list[low] = mid
quick_sort(data_list, start, low-1)
quick_sort(data_list, low+1, end)
return data_list
if __name__ == '__main__':
a = [10, 17, 50, 7, 30, 24, 27, 45, 15, 5, 36, 21, 20, 21, 21, 3294, 100]
data = quick_sort(a, 0, len(a)-1)
print(data)