Home > Backend Development > PHP Tutorial > PHP sorting algorithm (bubble sort, quick sort)_PHP tutorial

PHP sorting algorithm (bubble sort, quick sort)_PHP tutorial

WBOY
Release: 2016-07-21 15:15:44
Original
1104 people have browsed it

Bubble sort implementation principle

① First put all the numbers to be sorted into the work list.
② From the first number to the second to last number in the list, check one by one: if the number on a certain digit is greater than its next digit, swap it with its next digit.

③ Repeat step ② until no more exchanges are possible.

Code implementation

Copy code The code is as follows:

function bubbingSort(array $array )
{
for($i=0, $len=count($array)-1; $i<$len; ++$i)
{
for($j=$ lent; array[$j];
$array[$j] = $array[$j-1];
$array[$j-1] = $temp;
}
}
}
} return $array;
}

print '
';<br> print_r(bubbingSort(array(1,4,22,5,7,6,9) ));<br> print '
';



Quick sort implementation principle
Adopt the idea of ​​​​divide and conquer: first ensure that the first half of the list is smaller than the second half, and then sort the first half and the second half respectively, so that the entire list is in order.
Code implementation


Copy code

The code is as follows:function quickSort(array $array) {
$len = count($array);
if($len <= 1)
{
return $array;
}
$key = $array[0];
$left = array();
$right = array();
for($i=1; $i<$len; ++$i)
{
if($ array[$i] < $key)
                                                                                        [] = $ array[$i];
}
}
$left = quickSort($left);
$right = quickSort($right);
return array_merge($left, array($ key), $right);
}

print '
';<br> print_r(quickSort(array(1,4,22,5,7,6,9))) ;<br> print '
';






http://www.bkjia.com/PHPjc/326050.html

www.bkjia.com
truehttp: //www.bkjia.com/PHPjc/326050.html

TechArticleBubble sort implementation principle ① First put all the numbers to be sorted into the work list. ② From the first number to the second to last number in the list, check one by one: If the number on a certain digit...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template