PHP Quick Sort Small example php quick Sort Implementation method

Source: Internet
Author: User

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 if the array length is greater than 1
  4. $k = $arr [0]; The default Reference object is the first object of 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. Recursively arrange the arrays of the two sides separately
  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 records
  26. while (+ + $n <=300000) {
  27. $test _array[$n] = $n;
  28. }
  29. Echo ' Array init!
    ';
  30. Shuffle ($test _array); Scramble 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 sorting ideas: 1), the target array is divided into two arrays, the default is the first element as the benchmark, 2), if smaller than the reference object is assigned to the left array, otherwise assigned to right;3), according to this method assigned to know that there is only one element in the array.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.