In school, our teacher told us that the program data sorting will have a lot of algorithms, in fact, the bubbling algorithm is one of our commonly used sorting algorithm, the following I to use PHP to achieve bubble sort, the following record.
Example 1
| The code is as follows |
Copy Code |
|
/**
* Bubble sort (one-dimensional array)
* 22 Compare the size of the data element to be sorted, and find that two data elements are exchanged in reverse order until there are no reversed data elements
* Imagine a sorted array of R[1..N] vertically erected, each data element as a weight of bubbles, from the bottom of the scan array, where the principle of the scanning of light bubbles, so that it "floating upward." So repeated.
* Until the last of any two gases are light in the upper, the heavier is down.
*/
function Bubble_sort ($arr) {
$count = count ($arr);
if ($count = 0 | | is_array ($ARR)) {
Echo ' not NULL ARRAY ';
return false;
}
for ($i = 0; $i < $count; $i + +) {
$flag = 1;
for ($j = $count-1; $j > $i; $j-) {
if ($arr [$j] < $arr [$j-1]) {
$tmp = $arr [$j]; Swap the elements of an array
$arr [$j] = $array [$j-1];
$arr [$j-1] = $tmp;
$flag = 0;
}
if (1 = = $flag)
{
echo $i, ' finish sort ';
Break
}
}
}
return $arr;
} |
Example 2
| code as follows |
copy code |
|
!--? php
//Efficiency sort
//bubble Row < Select Sort < insert sort
$arr = array ( -1,10,99,89,77,101,3,4,5,22,11,56,32);
//Bubble sort
$flag = false;
Function Bubblesort ($myarr)
{
$_temp = 0;
for ($i =0; $i {
for ($j =0; $j {
//If the previous number ratio The number of polygons is large, then two number Exchange
if ($myarr [$j] > $myarr [$j +1])
{
$_temp = $myarr [$j];
$myarr [$j] = $myarr [$j +1];
$myarr [$j +1] = $_temp;
$flag = true;
}
}
//flage flag bit, increase efficiency with
if (! $flag)
{
echo "is already an ordered array";
break;//is already an ordered array, exit directly
}
$flag = false;
}
Return $myarr;
}
//output
Function dump ($string)
{
echo "
Print_r ($string); echo " ";
}
Dump (Bubblesort ($arr));
?>
|
http://www.bkjia.com/PHPjc/633162.html www.bkjia.com true http://www.bkjia.com/PHPjc/633162.html techarticle in school, our teacher told us that the program data sorting will have a lot of algorithms, in fact, the bubbling algorithm is one of our commonly used sorting algorithm, the following I have to use PHP to achieve bubble sort, the following to remember ...