Sorting PHP

To sort means to put a set of like items into order. The rules of ordering can be simple, such as strings sorted by the order of the alphabet. They could be complex, such as sorting addresses first by country, then by state, then by city. The process of sorting can take several forms but always involves comparing two elements with a set of rules for ordering. The result of the comparison determines whether the two items are in order or out of order, therefore needing to be swapped.

There are three classes of sorts: exchange, insert, and select. In an exchange method, two elements are compared and possibly exchanged. This process continues until the list is in order. In an insert method, the elements are removed and placed in another list, one by one. Each time an element is moved, it is inserted into the correct position. When all elements are moved, the list is in order. Last, a selection sort involves building a second list by scanning the first and repeatedly selecting the lowest value. Insertion and selection sorts are two sides of a coin. The former scans the new list; the latter scans the old list.

As I said earlier, a sorting algorithm is essentially comparison and possible movement of ements in a list. On average, moving elements around takes the same amount of time, no matter what algorithm you use. Likewise, the comparison is independent of the actual sort. If we take these to be constants, then the most important question to ask about each algorithm is: How many times does the algorithm perform either of these costly actions? Of course, the sort must be kept in context with the data. Some algorithms perform very well when the data are completely unordered but are slow when the data are already in order or in reverse order. Some sorts perform very poorly when there are many elements; others have such an overhead as to be inappropriate for smaller data sets. Like any technician, the programmer atches the tool to the job.



Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PHP Topics