PHP Sorting algorithm

Source: Internet
Author: User

Insert sort , starting from second position, one by one forward appropriate position (larger than left, smaller than right) insert

1<?PHP2 3 $ary=Array(39, 432, 5, 37, 43, 100, 32, 12);4 5  for($i= 1;$i<Count($ary);$i++) {6 7     $j=$i;8 9      while($j> 0 &&$ary[$j-1] >$ary[$j]) {Ten  One         $tmp=$ary[$j]; A         $ary[$j] =$ary[$j-1]; -         $ary[$j-1] =$tmp; -         $j--; the     } -  - } -  for($i= 0;$i<Count($ary);$i++) { +     Echo $ary[$i] . "<br/>"; - } +?>

Bubble sort, starting from the very end, and the previous comparison, will be small before the move, and finally the smallest placed in the first place.

Repeat once and put the small one in the second place ...

The result is finally reached

1<?PHP2 3 $ary=Array(39, 432, 5, 37, 43, 100, 32, 12);4 5  for($i= 0;$i<Count($ary);$i++) {6 7     $j=Count($ary)-1;8 9      while($j>$i) {Ten         if($ary[$j-1] >$ary[$j]) { One         $tmp=$ary[$j]; A         $ary[$j] =$ary[$j-1]; -         $ary[$j-1] =$tmp; -         } the         $j--; -     } -  - } +  for($i= 0;$i<Count($ary);$i++) { -     Echo $ary[$i] . "<br/>"; + } A?>

Select Sort, starting from the left, find the smallest and first swap positions, and from the second one, find the smallest and second swap positions, and repeat the results.

1<?PHP2 3 $ary=Array(39, 432, 5, 37, 43, 100, 32, 12);4 5              for($i= 0;$i<Count($ary)-1;$i++)6             {7                 $j=$i;8                 $minpos=$i;9                 $first=$ary[$i];Ten                  while($j<Count($ary)-1) One                 { A                     if($ary[$minpos] >$ary[$j+ 1]) -                     { -                         $minpos=$j+ 1; the                     } -                     $j++; -                 } -                 $ary[$i] =$ary[$minpos]; +                 $ary[$minpos] =$first; -             } +  A  for($i= 0;$i<Count($ary);$i++) { at     Echo $ary[$i] . "<br/>"; - } -?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.