I started reading ‘Introduction to Algorithms’ today, but I’ve gotten a bit confused over one of the exercises.
Exercise 1.2.2 asks the reader
Suppose we are comparing implementations of Merge sort and Insertion Sort on the same
machine. For inputs of size n, insertion sort runs in 8n^2 steps,
while merge sort runs in 64n log n steps.For which values of n does insertion sort beat merge sort?
I first tried opening up Wolfram Alpha and using it to draw graphs of the equations, but I couldn’t accurately compare the two graphs.
I then tried choosing a random value for n (200), working out the equations on paper, and then modifying the value of n based on my results.
But that took too long.
What is the correct way to solve this exercise?
See here: 8n2 = 64n log2 n. Just put both things in a single equation.
I.e., roughly n = 43 is the limit of insertion sort’s usefulness here.
Usually you would solve this by solving above equation f(n) = g(n) by solving f(n) − g(n) = 0, however, the analytical result in this case isn’t pretty as you’re mixing a polynomial with a logarithm function. I’d just try out a few values and see where the result flips from positive to negative. Once you have one positive and one negative point you can use bisection to narrow it down.
The brute-force way would be to simply try out all n up to a certain point. You already know that O(n2) algorithms aren’t suitable for large datasets, so the n has to be quite small. For my testing it looked like this:
(Excuse the horrible code; this was just a very quick doodle.)