Php bubble Sort and Quick sort instance detailed

Source: Internet
Author: User

$a =array (' 3 ', ' 8 ', ' 1 ', ' 4 ', ' One ', ' 7 ');p Rint_r ($a), $len = count ($a);//from Small to large for ($i =1; $i < $len; $i + +) {for ($j = $len-1; $j >= $i; $j-) if ($a [$j]< $a [$j-1]) {//If it is from large to small, if the judgment here is changed to if ($b [$j]> $b [$j-1]) $x = $a [$j]; $a [$j]= $a [$j-1]; $a [$j -1]= $x;}} Print_r ($a); j//another method from small to large $b=array (' 4 ', ' 3 ', ' 8 ', ' 9 ', ' 2 ', ' 1 '), $len =count ($b); for ($k =1; $k < $len; $k + +) {for ($j =$ Len-1, $i =0, $i < $len-$k, $i + +, $j-) if ($b [$j]< $b [$j-1]) {///if it is from large to small, as long as the judgment here is changed to if ($b [$j]> $b [$j-1]) $tmp = $b [$j]; $b [$j]= $b [$j-1]; $b [$j -1]= $tmp;} Print_r ($b); echo "";}  The following performance is more efficient function Maopao ($arr) {$len = count ($arr); for ($i =1; $i < $len; $i + +)//up to n-1 sequencing {$flag = false; The interchange flag should be false for ($j = $len-1; $j >= $i; $j-) {if ($arr-$j]< $arr [$j-1])//Exchange Record {///if it is from large to small, as long as the judgment here is changed to if ($arr [   $j]> $arr [$j-1]) can be $x = $arr [$j];   $arr [$j]= $arr [$j-1];   $arr [$j -1]= $x;   $flag = true;//swapped, so the swap flag is set to True} if (! $flag)//The current order does not occur, the early termination algorithm return $arr; }} $shuz = Array (' 2 ', ' 4 ', ' 1 ', ' 8 ', ' 5 '); $BB = Maopao ($shuz);p rint_r ($BB);//Quick Sort function KuaiSU ($arr) {$len = count ($arr);  if ($len <= 1) {return $arr;  } $key = $arr [0];  $left _arr = Array ();  $right _arr = Array ();    for ($i =1; $i < $len; $i + +) {if ($arr [$i] <= $key) {$left _arr[] = $arr [$i];    }else{$right _arr[] = $arr [$i];  }} $left _arr = Kuaisu ($left _arr);  $right _arr = Kuaisu ($right _arr); Return Array_merge ($left _arr, Array ($key), $right _arr);} $arr = Array (23,98,54,2,9,62,34);p Rint_r (Kuaisu ($arr));

Php bubble Sort and Quick sort instance detailed

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.