Is it possible? If not, given an array of size n, how do I know if its better to just sort the array?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
With just the unsorted array, there is no way to do this in sub-linear time. Since you don’t know which element is the largest and smallest, you have to look at them all, hence linear time.
The best sort you’ll find will be worse than that, probably relative to
n log nso it will be “better” to do the linear scan.There are other ways to speed up the process if you’re allowed to store more information. You can store the minimum and maximum using the following rules:
By doing it that way, probably the vast majority of retrieving min/max are constant time. It’s only when you’ve removed a value which was the min or max does the next retrieval require linear time for one retrieval.
The next retrieval after that will again be constant time since you’ve calculated and stored them, assuming you don’t remove the min/max value in the interim again.
Pseudo-code for just the maximum could be as simple as:
In that initialisation code above, we simply create the list and a maximum value and count. It would be easy to also add the minimum value and count as well.
To add to the list, we follow the rules above:
Deleting is quite simple. Just delete the value. If it was the maximum value, decrement the count of those maximum values. Note that this only makes sense if you know the current maximum – if not, you were already in the state where you were going to have to calculate it so just stay in that state.
The count becoming zero will indicate the maximum is now unknown (you’ve deleted them all):
Getting the maximum is then a matter of knowing when it needs to be calculated (when
maxcountis zero). If it doesn’t need to be calculated, just return it:All that pseudo-code uses seemingly global variables,
list,maxvalandmaxcount. In a properly engineered system, they would of course be instance variables so that you can run multiple lists side-by-side.