Usage environment and conditions
There is a situation where the associative array in PHP has the following array data:
[php]
$array = array (
array (
'name' => "xiao",
'age' => 3
),
array (
'name' => 'wang',
'age' => 1
),
array (
'name' => 'chen',
'age' => 2
) )
);
We want to sort the array against the age field. PHP’s built-in function, no matter what kind of sort, obviously cannot meet our needs, so we can write a quick sort code ourselves to quickly achieve our requirements.
There are no pointers in PHP, so when we want to pass by reference, we can't write quicksort (int *A, int begin, int end) directly like the C code. Instead, we have to use PHP's & operator. Pass the address of the array to the quick sort function, so that you can pass by reference instead of by value in PHP
Quick sort code
[php]
print_r ( $array );
/**
* Description: Get the position of the pivot point in quick sort
*/
function QuickPartition(&$array, $left, $right) {
// 1. Baseline definition
$stand = $array [$left];
// 2. Scan from both ends of the interval to the middle until $left == $right
while ( $left < $right ) {
While ( $left < $right && $array [$right] ['age'] >= $stand ['age'] ) {
$right --;
}
If ($left < $right) {
$array [$left ++] = $array [$right];
}
while ( $left < $right && $array [$left] ['age'] <= $stand ['age'] ) {
$left ++;
}
If ($left < $right) {
$array [$right --] = $array [$left];
}
}
// 3. Get the pivot point position
$array [$left] = $stand;
Return $left;
}
/**
* Description: Quick sort main process function
*/
function QuickSortProcess(&$array, $begin, $end) {
// 1. Variable definition
$pivot = NULL; // Pivot point
If ($begin < $end) {
$pivot = QuickPartition ($array, $begin, $end);
QuickSortProcess ( $array, $begin, $pivot - 1 );
QuickSortProcess ( $array, $pivot + 1, $end );
}
}
I used this quick sort in my project, and I was very happy. It was not in vain that I spent N days on the AC quick sort c code during the October 1st holiday