<?php $arr = array(‘r‘, ‘b‘, ‘w‘, ‘b‘, ‘b‘, ‘w‘, ‘r‘, ‘w‘, ‘r‘, ‘r‘, ‘b‘, ‘w‘); echo implode(‘--‘, $arr). "\n"; $wFlag = $bFlag = 0; $rFlag = count($arr) - 1; while($wFlag <= $rFlag){ if($arr[$wFlag] == ‘w‘){ $wFlag ++; }elseif($arr[$wFlag] == ‘b‘){ swap($arr, $wFlag, $bFlag); $wFlag++; $bFlag++; }else{ while($wFlag < $rFlag && $arr[$rFlag] == ‘r‘){ $rFlag--; } swap($arr, $wFlag, $rFlag); $rFlag--; } } echo implode(‘--‘, $arr). "\n"; function swap(&$arr, $x, $y){ $temp = $arr[$x]; $arr[$x] = $arr[$y]; $arr[$y] = $temp; }
时间: 2024-10-20 08:45:23