PHP
  Home arrow PHP arrow Page 4 - Collections and Sorting
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

Collections and Sorting
By: David Fells
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 21
    2006-03-28


    Table of Contents:
  • Collections and Sorting
  • Weighing the Options
  • Building the Foundation
  • Concrete Classes

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Collections and Sorting - Concrete Classes
    ( Page 4 of 4 )

    Now it is time to create an actual concrete implementation of the abstract Collection class and the ISortable interface. We will use a class called People for our collection. It will contain objects of the type Person. Really, it can contain any object implementing ISortable, but in our example we will only use the class Person. For now, the Person class is going to be just a glorified container for a single string, $name.

    class Person implements ISortable
    {
         private $name;
         public function GetName() { return $name; }
         public function SetName($name) { $this->name = $name;     }
         public function GetSortKey()
         {
              return $this->name;
         }    

         public function __construct($name)
         {
              $this->name = $name;
         }
    }

    Next we need to implement the People collection and its Sort() method. As I mentioned earlier in the article, there are quite a lot of ways to sort. For this example I will use the "fundamental" sort algorithm - the Bubble Sort. I should also point out that it is the slowest sort and should never be used on large data sets or where performance is a critical concern.

    class People extends Collection
    {
         public function Sort()
         {
              for ($i = $this->data->count() - 1; $i >= 0; $i--)
              {
                  $flipped = false;
                  for ($j = 0; $j < $i; $j++)
                  {
                       if (strcmp($this->data[$j]->GetSortKey(), 
                            $this->data[$j + 1]->GetSortKey()) > 0)
                       { 
                            $tmp = $this->data[$j];
                            $this->data->offsetSet($j, 
                                 $this->data[$j + 1]);
                            $this->data->offsetSet($j + 1, $tmp);
                            $flipped = true;
                       }
                  }
                  if (!$flipped)
                       return;
              }
         }
    }

    The Bubble Sort is by far the most obvious and intuitive sort algorithm, performing in-place swaps in a linear fashion. Notice that it will return early if any pass does not cause a swap - which means in an example like this one, it's just fine. Even if it did not return early, we will be working with so few elements that it simply does not matter. Consider the following example:

    $people = new People();
    $people->Append(new Person('Jamie'));
    $people->Append(new Person('David'));
    $people->Append(new Person('Natalie'));
    $people->Append(new Person('Johnny'));

    print '<pre>';

    print_r($people);

    $people->Sort();

    print_r($people);

    print '</pre>';

    You should see this in your browser after running the script:

    People Object
    (
        [data:protected] => ArrayObject Object
            (
                [0] => Person Object
                    (
                        [name:private] => Jamie
                    )
                [1] => Person Object
                    (
                        [name:private] => David
                    )
                [2] => Person Object
                    (
                        [name:private] => Natalie
                    )
                [3] => Person Object
                    (
                        [name:private] => Johnny
                    )
            )
    )
    People Object
    (
        [data:protected] => ArrayObject Object
            (
                [0] => Person Object
                    (
                        [name:private] => David
                    )
                [1] => Person Object
                    (
                        [name:private] => Jamie
                    )
                [2] => Person Object
                    (
                        [name:private] => Johnny
                    )
                [3] => Person Object
                    (
                        [name:private] => Natalie
                    )
            )
    )

    Conclusion

    There it is, a minimal implementation of collections with sorting. We have defined two interfaces and an abstract collection class and created a uniform way to sort within our collection. By sacrificing the ability to use an indexer on our collection, we were able to encapsulate the sort functionality within the collection class itself, sparing ourselves the trouble of creating even more classes.

    Having now implemented the worst possible sort algorithm and left an obvious re-factoring or two, the stage is set for the next installment of this article. In the next part we are going to actually implement a number of sort algorithms and benchmark them with a much larger data set. If you need to learn the fundamental sort algorithms (and all programmers do), be sure you check it out!



     
     
    >>> More PHP Articles          >>> More By David Fells
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek