In PHP
I have an array let say $array = array(2, 1, 8, 3, 6, 0, 10, 10)
and I want to get second largest value of that array.
Which sorting/searching technique will be best & how could I use it?
|
I'd just remove the duplicates from your array (using
The PHP manual has a comparison of sorting techniques. |
|||||
|
Something like this?
this reverse sorts the array and then outputs the second element. Edit: if you want the second highest unique value, just add an array_unique call:
|
|||||
|
you could use rsort, but it will do a lot of additional operations which are not needed (quick sort has O(logn) complexity). It might be a lot faster if you pass the array only in one pass like this (O(n)):
it will be significantly faster on large arrays, but it is only good when you want the first, second, maybe third largest element. In all other cases it would be more reasonable to sort the array and take the N'th largest element dynamically. |
|||||
|