PHP quick sort small example PHP quick sort implementation method
Full code:
-
- set_time_limit(0);
- function quickSort($arr) {
- if (count($arr) > 1) { // Only judge the case when the array length is greater than 1
- $k = $arr[0]; // The default reference object is the first object in the array
- $x = array(); // Smaller than the reference
- $y = array(); // Larger than the reference
- $_size = count($arr);
- for ($i = 1; $i < $_size; $i++) {
- if ($arr[$i] <= $k) {
- $x[] = $arr[ $i];
- } else {
- $y[] = $arr[$i];
- }
- }
- // Arrange the arrays on both sides recursively
- $x = quickSort($x);
- $y = quickSort($y);
- return array_merge($x, array($k), $y);
- } else {
- return $arr;
- }
- }
- $test_array = array();
- $n = 0;
- //Test a record of 300,000
- while(++$n<=300000){
- $test_array[$n] = $n;
- }
- echo 'Array init!
';
- shuffle($test_array); //Shuffle the order
- echo 'Array shuffled
';
- echo date( 'Y-m-d H:m:s').'
';
- $res = quickSort($test_array);
- echo date('Y-m-d H:m:s');
- ?>
Copy code
Quick sort idea:
1) Divide the target array into two arrays, with the first element as the basis by default;
2) If it is smaller than the reference object, it is allocated to the Left array, otherwise it is allocated to the Right array;
3) Follow this method until there is only one element in the array.
|