PHP Sort-quick sort-bubble sort-sort order

Source: Internet
Author: User

Quick Sort

\$arr = Array (32,31,56,4,234,46,466,86,5);

function Kuaisu (\$arr) {
if (!is_array (\$arr) | | empty (\$ARR)) {
return Array ();
}
Gets the length of the array
\$len = count (\$arr);

If there is only one element in the array, return the array directly
if (\$len <= 1) {
return \$arr;
}
\$key [0] = \$arr [0];
\$left = Array ();
\$right = Array ();

for (\$i =1; \$i < \$len; \$i + +) {
if (\$arr [\$i]<= \$key [0]) {
\$left []= \$arr [\$i];
}
else {
\$right [] = \$arr [\$i];
}
}

/* Print_r (\$left);
echo "<br>";
echo \$key [0];
echo "<br>";
Print_r (\$right);
echo "----------------*/

\$left = Kuaisu (\$left);
echo "\$right = Kuaisu (\$right);
/*
Print_r (\$left);
echo "<br>";
echo \$key [0];
echo "<br>";
Print_r (\$right);
echo "*/
Return Array_merge (\$left, \$key, \$right);
}
Print_r (\$arr);
echo "<br>";
echo "

Print_r (Kuaisu (\$arr));

Bubble sort

\$arr = Array (0,1,2,3,4,5,6,7,8,9);

\$len = count (\$arr)-1; Optimization

for (\$i = 0; \$i < \$len; \$i + +) {

for (\$j = 0; \$j < \$len-\$i; \$j + +) {

if (\$arr [\$j] < \$arr [\$j +1]) {

\$tmp = \$arr [\$j +1];

\$arr [\$j +1] = \$arr [\$j];

\$arr [\$j] = \$tmp;

}

}

}

Print_r (\$arr);

Sequential sorting

function Shunxu (\$arr) {
\$count = count (\$arr);
for (\$i =0; \$i < \$count-1; \$i + +) {
\$p = \$i;
for (\$j = \$i +1; \$j < \$count; \$j + +) {
\$p = \$arr [\$p] < \$arr [\$j]? \$j: \$p;
}
if (\$p! = \$i) {
\$tmp = \$arr [\$i];
\$arr [\$i] = \$arr [\$p];
\$arr [\$p] = \$tmp;
}
}
return \$arr;

}
Print_r (Shunxu (\$arr));

PHP Sort-quick sort-bubble sort-sort order

Related Keywords:

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.