Examples of PHP two sort algorithms. PHP two quick sorting algorithm examples this article mainly introduces two quick sorting algorithm examples in PHP. this article directly provides the implementation code, which are implemented by recursive method and iterative method, respectively, if you need a friend, you can use two quick sorting algorithms: PHP.
This article mainly introduces two examples of fast sorting algorithms in PHP. This article provides the implementation code using recursive and iterative methods. For more information, see
Although in web application development such as PHP, we do not emphasize the importance of sorting too much, because PHP has such powerful sorting functions as sort, however, in some important cases, such as high concurrency, I think the influence of sorting algorithms cannot be ignored. So here we will introduce recursive sorting and iterative sorting.
Recursion:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 |
/**
* Quick sorting implemented by recursive method
*/
Function quicksort ($ seq)
{
$ K = $ seq [0];
$ X = array ();
$ Y = array ();
For ($ I = 1; $ I <$ _ size; $ I ++ ){
If ($ seq [$ I] <= $ k ){
$ X [] = $ seq [$ I];
} Else {
$ Y [] = $ seq [$ I];
}
}
$ X = quicksort ($ x );
$ Y = quicksort ($ y );
Return array_merge ($ x, array ($ k), $ y );
} Else {
Return $ seq;
}
}
|
Iteration method:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 |
/**
* Fast sorting of iterative methods
*/
Function quicksortx (& $ seq)
{
$ Stack = array ($ seq );
$ Sort = array ();
While ($ stack ){
$ Arr = array_pop ($ stack );
If (count ($ arr) <= 1 ){
If (count ($ arr) = 1 ){
$ Sort [] = & $ arr [0];
}
Continue;
}
$ K = $ arr [0];
$ X = array ();
$ Y = array ();
$ _ Size = count ($ arr );
For ($ I = 1; $ I <$ _ size; $ I ++ ){
If ($ arr [$ I] <= $ k ){
$ X [] = & $ arr [$ I];
} Else {
$ Y [] = & $ arr [$ I];
}
}
! Empty ($ y) & array_push ($ stack, $ y );
Array_push ($ stack, array ($ arr [0]);
! Empty ($ x) & array_push ($ stack, $ x );
}
Return $ sort;
}
|
Usage:
?
|
1
2
3
4
5
6
7
8
9
10 |
/**
* Generate a random array
*/
For ($ I = 0; $ I <5; $ I ++ ){
$ TestArr [] = mt_rand (0,100 );
}
Var_dump ($ testArr );
Var_dump (quicksort ($ testArr ));
Var_dump (quicksortx ($ testArr ));
|
This article mainly introduces two examples of fast sorting algorithms in PHP. This article provides the implementation code, respectively using the recursive method and iterative method...