Today, I started to get some interview questions to consolidate my PHP knowledge and help some people looking for work.
Today, I started to get some interview questions to consolidate my PHP knowledge and help some people looking for work.
There are many functions related to arrays in PHP, including sorting by values (sort () and ksort ()), there are natural sorting (natsort () and so on, and the opposite reverse sorting. Next we will talk about the bubble sorting algorithm, which sorts an array by the value size. we can find that the function in PHP is actually a shorthand for some excellent custom algorithms.
The principle of bubble sorting: in a group of numbers, we compare them from the previous two to the next. each time we put a large number at the end, we will compare it for the next time. For example, for the four numbers 3, 1, 8, and 6, the first time starting from the first number, first compare 3 and 3 to 1, then put 3 behind 1, and then compare 3 and 8, put a large number behind it... in this way, compare them in sequence.
Can sum up the law: N number comparison, first from the first number, compare (N-1) times, then from the second number back comparison, comparison (N-2) times, and so on, write a UDF accordingly:
Function rev_array ($ array)
{
$ N = count ($ array );
For ($ I = $ N-1; $ I> 0; $ I --)
{
For ($ j = 0; $ j <$ I; $ j ++)
{
If ($ array [$ j]> $ array [$ j + 1])
{
$ Temp = $ array [$ j];
$ Array [$ j] = $ array [$ j + 1];
$ Array [$ j + 1] = $ temp;
}
}
}
Return $ array;
}
After reading it, I think it's quite simple. it's just taking test of our program algorithm.