1<?PHP2 //set the request header3 Header("Content-type:text/html;charset=utf-8");4 5 //optimize for bubbling sorting: If an array is passed in or traversed two times6 //It is already lined up and no more sorting is done7 8 ///Examples:9 $arr=Array(1,2,3,6,4,12,1,85,1,3);//WaitSort ArraysTen //$arr = range (1, 10000); One A functionMy_bubble_sort (&$arr){ - Var_dump($arr); - the $arr _count=Count($arr); - - //Number of comparisons - for($i= 0;$i<$arr _count-1;$i++){ + - for($j= 0;$j<$arr _count-$i-1;$j++){ + A //move big to the right, move small to the left (from big to small only need the symbol) at if($arr[$j] >$arr[$j+1]){ - //Swap Operations - $temp=$arr[$j]; - $arr[$j] =$arr[$j+ 1]; - $arr[$j+ 1] =$temp; - $flag= 1; in } - } to + if(!$flag){ - //If $flag=0 indicates that the small for loop has not been exchanged 1 times (without a single comparison, you can say that the array is sorted) the //You don't need to sort. * Break; $}Else{Panax Notoginseng $flag= 0; - } the } + A Var_dump($arr); the } + - $ $Date_default_timezone_set (' PRC '); - - //echo "Start:". Date (' H:i:s '). ' <br> '; theMy_bubble_sort ($arr); - //echo "End:". Date (' h:i:s ');Wuyi the?>
Sort by bubble sort (optimization)-php