I’m trying to keep track of number of comparison between array elements being made in merge sort. The program is written in Lua. I am trying to use multiple result and keep track of the counter but it isn’t working out. Is there other suggestions?
This is my first post so sorry if it’s messy. Thank you!
function merge_sort (src_array)
if #src_array <= 1 then
return src_array
else
local a1, a2 = split_array(src_array) -- splitting array to sort
return merge( -- merge the results recursively
merge_sort(a1),
merge_sort(a2))
end
end
If you want to do it using multiple results, you’ll need to change your recursive call.
Each function should return a sorted array together with the number of comparisons needed to sort it:
Your base case will look like
I think probably the extra result is not worth it and you are better off with a local counter and a nested
mergefunction: