Php plug-in sorting. -Php Tutorial

Source: Internet
Author: User
Php plug-in sorting. Baidu adopts the following plug-in sorting:

1 function insert_sort ($ arr) {2 // Sort $ arr in ascending order 3 $ count = count ($ arr); 4 for ($ I = 1; $ I <$ count; $ I ++) {5 $ tmp = $ arr [$ I]; 6 $ j = $ I-1; 7 while ($ j> = 0 & $ arr [$ j]> $ tmp) {8 $ arr [$ j + 1] = $ arr [$ j]; 9 $ j --; 10} 11 if ($ j + 1 )! = $ I) {12 $ arr [$ j + 1] = $ tmp; 13} 14} 15 return $ arr; 16}

It was really awkward to look at, and then I flipped through the algorithm written by Robert Sedgewick. the code in the book was implemented in java. here I will rewrite the plug-in sorting with php:

1 function new_insert_sort ($ arr) {2 // Sort $ arr in ascending order 3 $ count = count ($ arr); 4 for ($ I = 1; $ I <$ count; $ I ++) {// index, after one insertion, you need to move the index $ I right 5 // Insert arr [I] to a [i-1], a [i-2], a [I-3]... in, that is, if the condition is met, the switch location 6 for ($ j = $ I; $ j> 0 & $ arr [$ j] <$ arr [$ j-1]; $ j --) {7 $ tmp = $ arr [$ j]; 8 $ arr [$ j] = $ arr [$ j-1]; 9 $ arr [$ j-1] = $ tmp; 10} 11} 12 return $ arr; 13}

I think the second method is easier to understand, just as the algorithm says: plug-in sorting is like playing cards, insert each card to an appropriate position for other cards that have already been sorted. In addition, Baidu also found the blog Park's article Frank Fan's article plug-in sorting, you can also look at it.

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.