PHP implements four common sorting algorithms. InsertionSort and SelectionSort are the sort algorithms we often use. The following are the basic ideas and Insertion Sort of these algorithms. Selection Sort is a Sort algorithm that we often use. The following are the basic ideas of these algorithms and the corresponding PHP implementation code.
The basic idea of Insertion Sort is to insert a record to be sorted into the appropriate position of the subfile in the preceding sorted order according to its keyword size, until all records are inserted.
// Insert sorting (one-dimensional array) function insert_sort ($ arr) {$ count = count ($ arr); for ($ I = 1; $ I <$ count; $ I ++) {$ tmp = $ arr [$ I]; $ j = $ I-1; while ($ arr [$ j]> $ tmp) {$ arr [$ j + 1] = $ arr [$ j]; $ arr [$ j] = $ tmp; $ j -- ;}} return $ arr ;}
The basic idea of Selection Sort is: each trip selects the records with the smallest keyword from the records to be sorted, and puts the order at the end of the sorted subfile, until all records are sorted.
// Function select_sort ($ arr) {$ count = count ($ arr); for ($ I = 0; $ I <$ count; $ I ++) {$ k = $ I; for ($ j = $ I + 1; $ j <$ count; $ j ++) {if ($ arr [$ k]> $ arr [$ j]) $ k = $ j; if ($ k! = $ I) {$ tmp = $ arr [$ I]; $ arr [$ I] = $ arr [$ k]; $ arr [$ k] = $ tmp ;}} return $ arr ;}
The basic idea of bubble sorting is to compare the keywords of the records to be sorted in pairs. if the order of the two records is the opposite, the two records are exchanged until there is no reverse Order record.
// Bubble sort (one-dimensional array) function bubble_sort ($ array) {$ count = count ($ array); if ($ count <= 0) return false; for ($ I = 0; $ I <$ count; $ I ++) {for ($ j = $ count-1; $ j> $ I; $ j --) {if ($ array [$ j] <$ array [$ j-1]) {$ tmp = $ array [$ j]; $ array [$ j] = $ array [$ j-1]; $ array [$ j-1] = $ tmp ;}} return $ array ;}
Fast sorting is essentially the same as bubble sorting. it is an application of exchange sorting. So the basic idea is the same as the above bubble sorting.
// Function quick_sort ($ array) {if (count ($ array) <= 1) return $ array; $ key = $ array [0]; $ left_arr = array (); $ right_arr = array (); for ($ I = 1; $ I
Sort (Insertion Sort), select Sort (Selection Sort), bubble Sort and quick Sort are the Sort algorithms we often use. The following are the basic ideas and mappings of these algorithms...