Click Complexity and then Measure: the program runs for n = 10 … 500 with n random numbers, and the chart shows how many lines it runs. Bubble sort grows like O(n²). Click Keep for comparison, then measure merge sort below: O(n log n) on the same chart is far lower.
Bubble sort:
n = int(input())
a = list(map(int, input().split()))
for i in range(n - 1):
for j in range(n - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
print(a[:10])
6 5 2 8 1 9 3
Merge sort:
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
out = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
return out + left[i:] + right[j:]
n = int(input())
a = list(map(int, input().split()))
print(merge_sort(a)[:10])
6 5 2 8 1 9 3