Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

//print array
print("

Unsorted

\n");
print("
");
print_r($data);
print("
\n");


//sort array
Quicksort(&$data, 0, count($data)-1);


//print array again
print("

Sorted

\n");
print("
");
print_r($data);
print("
\n");
?>


The next step is to divide the list into two halves. Starting from the outside, elements are
checked for being greater than or less than the pivot. When two elements are found that
are both on the wrong side, they are swapped. When the left and right pointers meet, each
side is fed back to the quicksort function.


Built-In Sorting Functions


Usually it will not be necessary to write your own sort functions. PHP offers several
functions for sorting arrays. The most basic is sort. This function is described, along


with the other sorting functions, in Chapter 9, "Data Functions." It will be
instructive to compare sort to rsort , asort , and ksort.


The sort function puts all the elements in the array in order from lowest to highest. If
the array contains any strings, then this means ordering them by the ASCII codes of each
character. If the array contains only numbers, then they are ordered by their values. The
indices—the values used to reference the elements—are discarded and replaced with
integers starting with zero. This is an important effect, which Listing 15.3
demonstrates. Notice that, although I use some numbers and a string to index the array,
after I sort it, all the elements are numbered zero through four. Keep this in mind if you
ever need to clean up the indices of an array.


Another point worth noting in Listing 15.3 is the order of the output: Apple, Blueberry,
Watermelon, apple, pear. A dictionary might list apple just before or just after Apple, but
the ASCII code for A is 65. The ASCII code for a is 97. Appendix B lists all the ASCII
codes. Later in this chapter I'll explain how to code a case-insensitive sort.


The rsort function works exactly like sort, except that it orders elements in the


reverse order. Try modifying the code in Listing 15.3 by changing sort to rsort.

Free download pdf