Php bubble sorting $ A = array ('3', '8', '1', '4', '11', '7 ');
Print_r ($ );
$ Len = count ($ );
// From small to large
For ($ I = 1; $ I <$ len; $ I ++)
{
For ($ j = $ len-1; $ j >=$ I; $ j --)
If ($ a [$ j] <$ a [$ j-1])
{// If it is from large to small, just change the judgment here to if ($ B [$ j]> $ B [$ j-1 ]).
$ X = $ a [$ j];
$ A [$ j] = $ a [$ j-1];
$ A [$ j-1] = $ x;
}
}
Print_r ($ a); j
// Another method from small to large
$ B = array ('4', '3', '8', '9', '2', '1 ');
$ Len = count ($ B );
For ($ k = 1; $ k <$ len; $ k ++)
{
For ($ j = $ len-1, $ I = 0; $ I <$ len-$ k; $ I ++, $ j --)
If ($ B [$ j] <$ B [$ j-1]) {
// If it is from large to small, just change the judgment here to if ($ B [$ j]> $ B [$ j-1 ]).
$ Tmp = $ B [$ j];
$ B [$ j] = $ B [$ j-1];
$ B [$ j-1] = $ tmp;
}
Print_r ($ B );
Echo"
";
}
// The execution efficiency below is higher
Function maopao ($ arr)
{
$ Len = count ($ arr );
For ($ I = 1; $ I <$ len; $ I ++) // A maximum of n-1 sequential orders can be performed.
{
$ Flag = false; // The switching flag should be false before the sorting starts.
For ($ j = $ len-1; $ j >=$ I; $ j --)
{
If ($ arr [$ j] <$ arr [$ j-1]) // exchange records
{// If it is from large to small, just change the judgment here to if ($ arr [$ j]> $ arr [$ j-1 ]).
$ X = $ arr [$ j];
$ Arr [$ j] = $ arr [$ j-1];
$ Arr [$ j-1] = $ x;
$ Flag = true; // The switch flag is set to true because the switch is switched.
}
}
If (! $ Flag) // The algorithm is terminated before the current sorting is exchanged.
Return $ arr;
}
}
$ Shuz = array ('2', '4', '1', '8', '5 ');
$ Bb = maopao ($ shuz );
Print_r ($ bb );
// Quick sorting
Function kuaisu ($ arr ){
$ Len = count ($ arr );
If ($ len <= 1 ){
Return $ arr;
}
$ Key = $ arr [0];
$ Left_arr = array ();
$ Right_arr = array ();
For ($ I = 1; $ I <$ len; $ I ++ ){
If ($ arr [$ I] <= $ key ){
$ Left_arr [] = $ arr [$ I];
} Else {
$ Right_arr [] = $ arr [$ I];
}
}
$ Left_arr = kuaisu ($ left_arr );
$ Right_arr = kuaisu ($ right_arr );
Return array_merge ($ left_arr, array ($ key), $ right_arr );
}
$ Arr = array (, 34 );
Print_r (kuaisu ($ arr ));
?>