Three sorting methods of arrays in PHP, three sorts of PHP arrays
Description: Find the maximum number, arrange it to the last face, and then continue looking for an example: $arr = Array (3,5,-1,0,2); for ($i =0; $i $arr [$j +1]) {$temp = $arr [$j]; $arr [$j]= $arr [$j +1]; $arr [$j +1]= $temp;}} Understanding: 3,5,-1,0,2//From the beginning of the first number to compare, if the number is larger than the following and the next number of positions//First, 3 is less than 5, then the same//second, 5 greater than 1, then become 3,-1,5,0,2//third, 5 greater than 03,-1,0,5,2//fourth time , 5 is greater than 23,-1,0,2,5 to complete a loop at this time, the last number completes the sorting, the next time will not participate in the 3,-1,0,2,5 second outer loop starts first: 3 is greater than -1-1,3,0,2,5 second time: 3 is greater than 0-1,0,3,2,5 third time: 3 is greater than 2-1, 0,2,3,5 this to complete the next two digits of the sort, and then -1,0,2,3,5 second, the choice of sorting method Description: First assume that the first number is the smallest number, and then the following number and then compare it, if the number is not the smallest number, it will be replaced with the smallest number of the following position $arr= Array (2,1,-1,3,0); for ($i =0; $i =0 && $insertval < $arr [$insertindex]) {$arr [$insertindex +1]= $arr [$insertindex]; $insertindex--;} $temp = $ arr[$i]; $arr [$insertindex +1]= $insertval;} Understanding: 2,1,-1,3,0////First, save the number to be inserted 1 for insertval, then take Insertval and 2 comparison, 1 is less than 2, so put 2 back, into the following figure 2,2,-1,3,0//At this time 2 there is no number, insertindex= 0, so the comparison is complete, then insert the insertval into the found position. Become like 1,2,-1,3,0//At this time, you become an ordered array//The second time, save the number to be inserted-1 for Insertval, then take insertval and 2 to compare, 1 less than 2, so put 2 back, become like 1,2,2,3,0//at this time, Then take insertval compared with 1,-1 is less than 1, then put-1 back, turn into as (this is a number to be inserted with the previous sequential array comparison process) 1,1,2,3,0//At this time, Insertindex to the end, so insertval insert the position-1, 1,2,3,0//behind-the-push method above
http://www.bkjia.com/PHPjc/1115252.html www.bkjia.com true http://www.bkjia.com/PHPjc/1115252.html techarticle PHP Array of three sorting methods, PHP array Three sort description: Find the largest number, arrange to the last side, and then continue to find examples: $arr = array (3,5,-1,0,2); for ($i =0; $icount ($arr)-1;