Ejemplo n.º 1
0
 /**
  * Comb sort: A variation on bubble sort that dramatically improves performance.
  *Source: http://yagni.com/combsort/
  *Requirements: Needs to be able to compare elements with <=>, and the [] []= methods should
  *be implemented for the container.
  *Time Complexity: О(n^2)
  *Space Complexity: О(n) total, O(1) auxiliary
  *Stable: Yes
  *
  *@param array $arr Array to be sorted
  *@return array
  */
 public static function comb_sort($arr)
 {
     $gap = floor(count($arr) / Sort::$SHRINK_FACTOR);
     while ($gap > 0) {
         for ($i = 0; $i < count($arr) - $gap; ++$i) {
             $arrWithGapsKeys = array();
             $arrWithGaps = array();
             $loop = true;
             $j = $i;
             while ($loop) {
                 if (isset($arr[$j])) {
                     $arrWithGapsKeys[] = (int) $j;
                     $arrWithGaps[] = $arr[$j];
                     $j += $gap;
                 } else {
                     $loop = false;
                 }
             }
             $arrWithGapsOrdered = Sort::bubble_sort($arrWithGaps);
             foreach ($arrWithGapsKeys as $key) {
                 $arr[$key] = current($arrWithGapsOrdered);
                 next($arrWithGapsOrdered);
             }
         }
         $gap = floor($gap / Sort::$SHRINK_FACTOR);
     }
     return $arr;
 }