时间复杂度所耗费的时间从小到大依次是
O(1)< O(logn) < O(n) < O(n*logn) < O(n^2) < O(n^3) < O(2^n) < O(n!) < O(n^n)
斐波那契数列
# 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)
冒泡排序
时间复杂度O(n^2)
# encoding=utf-8
def bubble_sort(data_list):
for i in range(len(data_list)-1): # i代表需要冒泡循环比较的次数
for j in range(len(data_list)-i-1): # j代表循环到的下标位置
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 = bubble_sort(a)
print(data)
选择排序
时间复杂度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)
插入排序
时间复杂度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: 起始元素下标
:param end: 结束元素下标
: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)