Comb sort or comb sort is a variant ofBubble sort. Similar toShell sort, Comb Sort increases the gap used in comparisons and exchanges. Some implementations use insertion sort when the interval is less than a certain number. The basic idea is to eliminate small values near the end of the list, since in bubble sort these will slow down the sort significantly. And large values at the beginning of the list will not cause problems in bubble sort.
In bubble sort, when any two elements are compared, they always have a gap of 1. The basic idea of comb sorting is that the gap can be much larger than 1.
PHP comb sorting diagram is as follows:
##The code example is as follows:
1 || $swap){ if($gap > 1) $gap /= 1.25; $swap = false; $i = 0; while($i+$gap < count($my_array)){ if($my_array[$i] > $my_array[$i+$gap]){ list($my_array[$i], $my_array[$i+$gap]) = array($my_array[$i+$gap],$my_array[$i]); $swap = true; } $i++; } } return $my_array; } $test_array = array(3, 0, 2, 5, -1, 4, 1); echo "原始数组 :\n"; echo implode(', ',$test_array ); echo "\n排序后数组\n:"; echo implode(', ',combSort($test_array)). PHP_EOL;
原始数组 : 3, 0, 2, 5, -1, 4, 1 排序后数组 :-1, 0, 1, 2, 3, 4, 5
The above is the detailed content of Implementation of PHP Comb Sort algorithm. For more information, please follow other related articles on the PHP Chinese website!