Skip to content

Insertion sort algorithm PHP implementation

2012 June 19
by Richard Knop

This is a third blog post in my challenge to cover as many sorting algorithms as possible, implement them in PHP (without using any array functions) and then benchmark their performance with different inputs. Could be interesting.

Insertion sort is another common sorting algorithm. To explain how it works, try to imagine this. There’s a couple of cards on the table and you want to sort them in a correct order. You will pick a card from the table (based on any criteria, it doesn’t really matter, you can just pick the cards up randomly) and put it in your left hand at a correct position. To determine the correct position, you will compare it with every other card in your left hand starting from the right. This is a similar algorithm you might unconsciously use when playing cards with your friends.

Example:

  1. <?php
  2.  
  3. $table = array(7, 3, 9, 6, 5, 1, 2, 0, 8, 4);
  4. $leftHand = insertionSort($table);
  5. var_dump($leftHand);
  6.  
  7. function insertionSort(array $table) {
  8.     $leftHand = array();
  9.     foreach ($table as $card) {
  10.         if (0 === count($leftHand)) {
  11.             $leftHand[] = $card;
  12.         } else {
  13.             $insertedCard = false;
  14.             $reindexedLeftHand = array();
  15.             for ($i = count($leftHand)-1; $i >= 0; $i) {
  16.                 if ($card >= $leftHand[$i]) {
  17.                     for ($j = 0; $j <= $i; ++$j) {
  18.                         $reindexedLeftHand[$j] = $leftHand[$j];
  19.                     }
  20.                     $reindexedLeftHand[] = $card;
  21.                     for ($j = $i+1; $j < count($leftHand); ++$j) {
  22.                         $reindexedLeftHand[$j+1] = $leftHand[$j];
  23.                     }
  24.                     $insertedCard = true;
  25.                     break;
  26.                 }
  27.             }
  28.             if (false === $insertedCard) {
  29.                 $reindexedLeftHand[] = $card;
  30.                 foreach ($leftHand as $cardInLeftHand) {
  31.                     $reindexedLeftHand[] = $cardInLeftHand;
  32.                 }
  33.             }
  34.             $leftHand = $reindexedLeftHand;
  35.         }
  36.     }
  37.     return $leftHand;
  38. }

Will result in:

array(10) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
  [5]=>
  int(5)
  [6]=>
  int(6)
  [7]=>
  int(7)
  [8]=>
  int(8)
  [9]=>
  int(9)
}

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS