I’ve got an array of n elements. Those elements are numbers. What I have to do now is find a lot of them in my array. I will have to make about sqrt(n) searches.
What is a better option for me from efficiency point of view?
- Linear search
- Array Sorting (lets say in linear time, it is possible when we use RadixSort for example) and then searching the elements with binary-search –
O(logn)
I’ve got some intuitions, but I dont know how to check and proof it. Linear search cost is (in worst case) : O(n) * O(sqrt(n)). Binary-search after sorting would be O(n) + O(logn) * O(sqrt(n)).
As you said, you have two options:
sqrt(n)times. Cost isO(n * sqrt(n)).O(n)and then binary searchsqrt(n)times.Cost is
O(n + log(n) * sqrt(n)).nis bigger thenlog(n) * sqrt(n)for all positiven. Proof.Thanks to this, we can write
O(n + log(n) * sqrt(n)) = O(n).Sorting part is dominating, it’s the bottleneck.
So, second approach, for big
n, should be faster – approximately linear.