Is it better to sort then binary search or simply linear search?
Thanks
Is it better to sort then binary search or simply linear search?
Thanks
No, because Quick Sort is slower than linear, and you add some more.
O(n*log(n)) + O(log(n)) = O(n*log(n)) > O(n)
Edit: Not precisely correct as pointed out, as worst case of Quick Sort is even slower with O(n^2). n*log(n) is best case and average case, which provides a lower bound is already slower than linear. The correct symbol might though be Θ instead of O.
It depends how often you want to search after the sort - if only once, then a linear search will probably be faster. Of course, an even better bet is normally (but not always) to maintain things in sorted order using something like set or a map.
It depends on the input. Linear search is usually faster for small number of elements.
Linear search is O(n), sorting is O(n log n), binary search is O(log n). Thus, if you expect to search more than log n times, sorting is better. (Of course this is just theoretical performance, on practice you're also interested in constants, esp. for not-too-large n)
Forgetting the binary search for a minute:
Quick sort best case: O(n log n)
Quick sort worst case: O(n^2)
Linear search worst case: n
So regardless of what you do after quick sort, you'd already have found the item if you'd done a linear search. However, this only holds for the first search. Say you had more than one search to do. If you retain the (Quick)sorted list, then all following searches have a worst case of O (log n)
, so over several searches (particularly on larger datasets), sorting and searching would be wise. As always with programming and software design in general, there is never a 'one size fits all', so thinking about what patterns and implementations are most appropriate to your particular domain in essential.