Example _php of PHP two quick sort algorithm

Source: Internet
Author: User

Although in the development of Web applications such as PHP, we do not emphasize the importance of ordering, because PHP itself has brought such as sort () and so powerful sorting functions, but on some important occasions, such as some high concurrency, I think the impact of the sorting algorithm can not be ignored. So here we introduce recursive sorting and iterative sorting.

Recursive method :

/**
* Recursive method to achieve fast ordering
/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:

/**
* Fast ordering of iterative method
/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;
}

Use:

/**
* Generates a random array of * * for
($i =0; $i <5; $i + +) {
  $testArr []=mt_rand (0,100);
}
Var_dump ($TESTARR);
Var_dump (Quicksort ($TESTARR));

Var_dump (Quicksortx ($TESTARR));

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.