PHP Instance code: All sorts of algorithms

Source: Internet
Author: User
Tags sorts

  

Bubble sort

function Maopao_sort ($demo) {

$num = count ($demo);

for ($i =0; $i < $num; $i + +) {

for ($j = $num-1; $j > $i; $j-) {

if ($demo [$j]< $demo [$j-1]) {

$temp = $demo [$j];

$demo [$j]= $demo [$j-1];

$demo [$j -1]= $temp;

}

}

}

return $demo;

}

Insert Sort

function Charu_sort ($demo) {

$num = count ($demo);

for ($i =1; $i < $num; $i + +) {

$temp = $demo [$i];

$dqweizhi = $i -1;//record current position

while ($dqweizhi >=0) && ($temp < $demo [$dqweizhi])) {

$demo [$dqweizhi +1] = $demo [$dqweizhi];

$dqweizhi--;

}

$demo [$dqweizhi +1] = $temp;

}

return $demo;

}

Sorting by Selection method

function Select_sort ($demo) {

$num = count ($demo);

For ($i =0 $i < $num-1; $i + +) {

$temp = $demo [$i];

$dqweizhi = $i;

for ($j = $i +1; $j < $num; $j + +) {

if ($demo [$j]< $temp) {

$temp = $demo [$j];

$dqweizhi = $j;

}

}

$demo [$dqweizhi]= $demo [$i];

$demo [$i]= $temp;

}

return $demo;

}

Quick Sort

function Quick_sort ($demo)

{

$num = count ($demo);

if ($num <=1) {

return $demo;

}

$key = $demo [0];

$left _array=array ();

$right _array=array ();

for ($i =1; $i < $num; $i + +) {

if ($demo [$i]<= $key) {

$left _array[]= $demo [$i];

}else{

$right _array[]= $demo [$i];

}

}

$left _array =quick_sort ($left _array);

$right _array=quick_sort ($right _array);

Return Array_merge ($left _array,array ($key), $right _array);

}

$test = Array (' 43 ', ' 154 ', ' 3 ', ' 78 ', ' 13 ', ' 284 ', ' 167 ', ' 2 ', ' 56 ', ' 2234 ', ' 121 ', ' 57 ', ' 345 ');

$sss = Quick_sort ($test);

Var_dump ($SSS);

?>

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.