用Python做常见算法时间函数的增长趋势分析的代码
时间: 2024-04-27 15:05:59 浏览: 88
下面是一个简单的Python代码示例,用于分析常见算法的时间复杂度增长趋势:
```python
import time
import random
import matplotlib.pyplot as plt
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
left = []
right = []
for i in range(1,len(arr)):
if arr[i] < pivot:
left.append(arr[i])
else:
right.append(arr[i])
return quick_sort(left) + [pivot] + quick_sort(right)
def generate_random_array(n):
return [random.randint(1, 100) for _ in range(n)]
def time_function(func, n):
arr = generate_random_array(n)
start_time = time.time()
func(arr)
end_time = time.time()
return end_time - start_time
def plot_time_complexity(func, n_values):
times = [time_function(func, n) for n in n_values]
plt.plot(n_values, times)
plt.title(func.__name__)
plt.xlabel('Input size')
plt.ylabel('Time (seconds)')
plt.show()
n_values = [10, 100, 1000, 10000, 100000]
algorithms = [bubble_sort, selection_sort, insertion_sort, merge_sort, quick_sort]
for algorithm in algorithms:
plot_time_complexity(algorithm, n_values)
```
该代码通过使用 `time` 模块计算不同输入大小的算法运行时间,并使用 `matplotlib` 库绘制算法运行时间与输入大小之间的关系图表。在这个例子中,我们测试了冒泡排序、选择排序、插入排序、归并排序和快速排序算法的运行时间。
阅读全文