I am currently trying to get the values that are in the lowest half of an array of data. This array in unsorted at first.
From this:
{4,6,9,3,8,5}
To this :
{3,4,5,6,9,8} or {3,4,5}
An easy solution would be to sort the array (using quicksort) and then use only the values stored in the first half of the sorted array.
However, since quicksort and most efficient sorting algorithms will sort the entire array while I only need the first 50%, this seems like a waste of ressources. Note that performance is an issue in this project.
Knowing that a full sort is O(n log n) and that a sort that stops after it finds the lowest element is O(n), I can easily build a simple algorithm that will have a complexity of n/2 * n to find the lowest 50%. But is that really better than a full quicksort?
To be clear, what would be the best sort to use if we want only the lowest half of the values in an array?
If the 50% was smaller (like 1%), a sequential search of the lowest elements would of course be the fastest solution, but at what % does it become slower than a quicksort?
I am coding in C++ and using vectors, but this question should be pretty general.
1 Answer