Sorting Anything


 function compare($a, $b) {   return $a - $b; } $a = array(4, 1345, 31, 222); usort($a, 'compare'); echo implode(' < ', $a); 


If you do not want to limit yourself to the standard sorting functionality offered by PHP, you can write your own sorting algorithm. Internally, PHP uses the Quicksort algorithm to sort values in an array. For this to work, PHP has to know if two values are equal; in the latter case, PHP needs to find out which value is greater. So, to implement a custom sort, all that is required is a function that takes two parameters and returns:

  • A negative value if the first parameter is smaller than the second parameter

  • 0 if both parameters are equal

  • A positive value if the second parameter is smaller than the first parameter

The name of this function must be passed to usort()as a string! The rest of the work is done by PHP, as can be seen in the code. The comparison function used there is a very simple way to do a numeric sorting. By substracting the two values, the function returns the desired values: A positive number if the first parameter is larger than the second one, 0 if both parameters are equal, and a negative number otherwise.

NOTE

The Quicksort algorithm is one of the fastest algorithms to sort elements. When sorting n elements, it uses up to n? comparisons to do so; however, on average, only n log n comparisons are needed, making it really quick. Quicksort uses a divide-and-conquer strategy: It splits a problem into several smaller subproblems that can be solved recursively. More information about this algorithm can be found at http://en.wikipedia.org/wiki/Quicksort.





PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net