I've tried to count the done operations in a algorithm the following way
def selection_sort(arr):
ops = 0 # The number of done operations
for i in range(0, len(arr)):
ops += 1
least_idx = i
ops += 1
for j in range(i, len(arr)):
ops += 1
if arr[j] < arr[least_idx]:
ops += 1
least_idx = j
ops += 1
arr[i], arr[least_idx] = arr[least_idx], arr[i]
ops += 3
return ops
Is it correct? And if it is, how to do it for a recursive algorithm like merge sort? And as for the runtime, I'm afraid that caching of the previous results will impact the next ones. The testing process is the following:
from random import sample
sort_algos = [selection_sort, insertion_sort, merge_sort]
for algo in sort_algos:
for n in range(7, 8):
arr = sample(range(0, 2**n), 2**n)
algo(arr)
And in the end I want to have measures of the results for each n. Thank you in advance.