Home >Backend Development >PHP Tutorial >Sort PHP array using bead algorithm
In "Brief Analysis of How to Sort Integer Arrays through PHP Classes", we introduce how to use PHP classes to sort arrays. So this article will introduce to you an interesting bead algorithm and use it to sort PHP arrays.
First of all, let me briefly introduce to you what is the abacus algorithm?
The bead algorithm, also called bead sorting, is a natural sorting algorithm developed by Joshua J. Arulanandham, Cristian S. Calude and Michael J. Dinneen in 2002, and was used in European theoretical computers. The algorithm was published in a press briefing of the European Association for Theoretical Computer Science (EATCS).
Both digital and analog hardware implementations of bead sorting can achieve O(n); however, implementations of this algorithm tend to be much slower in software and can only be used to sort lists of positive integers.
After a brief understanding of the algorithm, we directly code:
<?php function columns($uarr) { $n=$uarr; if (count($n) == 0) return array(); else if (count($n) == 1) return array_chunk($n[0], 1); array_unshift($uarr, NULL); $transpose = call_user_func_array('array_map', $uarr); return array_map('array_filter', $transpose); } function bead_sort($uarr) { foreach ($uarr as $e) $poles []= array_fill(0, $e, 1); return array_map('count', columns(columns($poles))); } echo '原始数组: '.' '; var_dump(array(5,3,1,3,8,7,4,1,1,3)); echo ' '.'珠排序后 : '.' '; var_dump(bead_sort(array(5,3,1,3,8,7,4,1,1,3)));
The running results are as follows:
In the above code, I will introduce you to several key functions:
1, array_unshift()
function: used to insert new elements into the array. The values of the new array will be inserted at the beginning of the array. The added elements are added as a whole, in the same order in the array as in the parameters. This function returns the number of elements in the array.
2, c
all_user_func_array
: Call the callback function and use an array parameter as the parameter of the callback function. The syntax is "call_user_func_array(callable $callback, array $param_arr): mixed
" means calling the first parameter as the callback function (callback), and passing the parameter array (param_arr) as the parameter of the callback function.
3, array_map
: Apply a callback function to each element of the array.
Finally, I would like to recommend to you the latest free course on our platform "Entering the World of PHP from 0"~ Come and learn!
The above is the detailed content of Sort PHP array using bead algorithm. For more information, please follow other related articles on the PHP Chinese website!