Examples of PHP two sort algorithms

Source: Internet
Author: User
This article mainly introduces two examples of fast sorting algorithms in PHP. This article provides the implementation code, which are implemented by recursive method and iterative method, respectively, for more information, see. although we do not emphasize the importance of sorting in web application development such as PHP, PHP has already brought () such a powerful sorting function, but in some important scenarios, such as high concurrency, I think the impact of sorting algorithms can no longer be ignored. So here we will introduce recursive sorting and iterative sorting.

Recursion:

/*** Quick sorting implemented by recursive method */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 sorting of iterative methods */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 ;}

Usage:

/*** Generate a random array */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.