PHP bubble sorting algorithm example. At school, our teacher told us that there will be many algorithms for program data sorting. In fact, the bubble algorithm is a commonly used sorting algorithm. next I will use php to Implement Bubble sorting, the following is a description of the algorithm used to sort program data. In fact, the bubble algorithm is a common sorting algorithm. next I will use php to Implement Bubble sorting, record it below.
Example 1
| The code is as follows: |
|
|
/**
* Bubble sorting (one-dimensional array)
* Compare the size of the elements to be sorted. if the two data elements are in the opposite order, they are exchanged until there is no data element in the reverse order.
* Imagine the sorted array R [1 .. n] Vertical vertical erect, each data element is considered as a bubble with weight, scanning the array from bottom up, where a light bubble that violates the principle is scanned, it will "float" up ". this is repeated.
* Until the last two parties are put on the lighter ones, the heavier ones will be placed on the lighter ones.
*/
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 the array
$ Arr [$ j] = $ array [$ j-1];
$ Arr [$ j-1] = $ tmp;
$ Flag = 0;
}
If (1 = $ flag)
{
Echo $ I, 'sorting completed ';
Break;
}
}
}
Return $ arr;
} |
Example 2
| The code is as follows: |
|
|
// Sort efficiency
// Bubble sort <select sort <insert sort
$ Arr = array (-77,101, 32 );
// Bubble sort
$ Flag = false;
Function bubbleSort ($ myarr)
{
$ _ Temp = 0;
For ($ I = 0; $ I
{
For ($ j = 0; $ j
{
// If the preceding number is greater than the latter, the two numbers are exchanged.
If ($ myarr [$ j]> $ myarr [$ j + 1])
{
$ _ Temp = $ myarr [$ j];
$ Myarr [$ j] = $ myarr [$ j + 1];
$ Myarr [$ j + 1] =_ _ temp;
$ Flag = true;
}
}
// Flage flag space to improve efficiency
If (! $ Flag)
{
Echo "already an ordered array ";
Break; // it is already an ordered array and exits directly.
}
$ Flag = false;
}
Return $ myarr;
}
// Original output
Function dump ($ string)
{
Echo"
"; print_r($string); echo " ";
}
Dump (bubbleSort ($ arr ));
?>
|
...