PHP bubble sorting algorithm

Source: Internet
Author: User
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.

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.