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.