PHP quick sort small example PHP quick sort implementation method

WBOY
Release: 2016-07-25 09:11:53
Original
1056 people have browsed it

PHP quick sort small example PHP quick sort implementation method

Full code:

  1. set_time_limit(0);
  2. function quickSort($arr) {
  3. if (count($arr) > 1) { // Only judge the case when the array length is greater than 1
  4. $k = $arr[0]; // The default reference object is the first object in the array
  5. $x = array(); // Smaller than the reference
  6. $y = array(); // Larger than the reference
  7. $_size = count($arr);
  8. for ($i = 1; $i < $_size; $i++) {
  9. if ($arr[$i] <= $k) {
  10. $x[] = $arr[ $i];
  11. } else {
  12. $y[] = $arr[$i];
  13. }
  14. }
  15. // Arrange the arrays on both sides recursively
  16. $x = quickSort($x);
  17. $y = quickSort($y);
  18. return array_merge($x, array($k), $y);
  19. } else {
  20. return $arr;
  21. }
  22. }
  23. $test_array = array();
  24. $n = 0;
  25. //Test a record of 300,000
  26. while(++$n<=300000){
  27. $test_array[$n] = $n;
  28. }
  29. echo 'Array init!
    ';
  30. shuffle($test_array); //Shuffle the order
  31. echo 'Array shuffled
    ';
  32. echo date( 'Y-m-d H:m:s').'
    ';
  33. $res = quickSort($test_array);
  34. echo date('Y-m-d H:m:s');
  35. ?>
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.



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template