The code below is quicksort in Python. How do I count how many times comparison operates in the algorithm?
Although I assign count = 0 at first, it is reset to 0 because of recursion.
def QuickSort(lst):
if len(lst) > 1:
pivot_idx = len(lst) // 2
smaller_nums, larger_nums = [], []
for idx, num in enumerate(lst):
if idx != pivot_idx:
if num < lst[pivot_idx]:
smaller_nums.append(num)
else:
larger_nums.append(num)
QuickSort(smaller_nums)
QuickSort(larger_nums)
lst[:] = smaller_nums + [lst[pivot_idx]] + larger_nums
return lst
QuickSortfunction, although I'm not sure why you couldn't simply uselen(lst)instead ofcount.