Php sorting algorithm code, including bubble sorting and quick sorting. For more information about how to implement bubble sorting, see Bubble sorting.
① Put all the numbers to be sorted into the work list.
② From the first number in the list to the second to the last number, check one by one: if the number on a certain digit is greater than the next digit, then it is exchanged with its next digit.
③ Repeat step ② until the exchange is no longer allowed.
Code implementation
The code is as follows:
Function bubbingSort (array $ array)
{
For ($ I = 0, $ len = count ($ array)-1; $ I <$ len; ++ $ I)
{
For ($ j = $ len; $ j> $ I; -- $ j)
{
If ($ array [$ j] <$ array [$ j-1])
{
$ Temp = $ array [$ j];
$ Array [$ j] = $ array [$ j-1];
$ Array [$ j-1] = $ temp;
}
}
}
Return $ array;
}
Print'
';
print_r(bubbingSort(array(1,4,22,5,7,6,9)));
print '
';
Principles of quick sorting
The idea of sub-governance is adopted: 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 separately, so that the whole list is ordered.
Code implementation
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)
{
$ Left [] = $ array [$ I];
}
Else
{
$ Right [] = $ array [$ I];
}
}
$ Left = quickSort ($ left );
$ Right = quickSort ($ right );
Return array_merge ($ left, array ($ key), $ right );
}
Print'
';
print_r(quickSort(array(1,4,22,5,7,6,9)));
print '
';