InsertionSort.php 856 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <?php
  2. /**
  3. * @file
  4. * InsertionSort.php
  5. *
  6. * @author: marand
  7. *
  8. * @license General Public License version 2 or later
  9. */
  10. namespace OSInet\Sort;
  11. /**
  12. * Class InsertionSort
  13. *
  14. * @package OSInet\Sort
  15. *
  16. * @see http://en.wikipedia.org/wiki/Insertion_sort
  17. */
  18. class InsertionSort extends Sort {
  19. public function sort($data, $comparison, $options = array()) {
  20. $sorted = array();
  21. foreach ($data as $unsorted_offset => $unsorted_value) {
  22. $found = false;
  23. foreach ($sorted as $sorted_offset => $sorted_value) {
  24. $result = $comparison($unsorted_value, $sorted_value);
  25. if ($result < 0) {
  26. $found = true;
  27. array_splice($sorted, $sorted_offset, 0, array($unsorted_value));
  28. break;
  29. }
  30. }
  31. if (!$found) {
  32. $sorted[] = $unsorted_value;
  33. }
  34. }
  35. return $sorted;
  36. }
  37. }