PHP array bubble sort algorithm instance code

Source: Internet
Author: User
Bubble sort (Bubble sort) is a simpler sort algorithm in the field of computer science.

It repeatedly visited the sequence to sort, comparing two elements at a time, and swapping them out if they were wrong in the order. The work of the sequence of visits is repeated until no more need to be exchanged, that is, the sequence is sorted.

The algorithm is named because the larger the element will slowly "float" through the switch to the top of the sequence,

This article mainly introduces the PHP array bubble sorting algorithm, with a simple instance of the PHP array bubble sorting algorithm implementation principles and related skills, the need for friends can refer to the following :

<?php/*@ Bubble Sorting algorithm */$array =array (5,45,22,11,32,28,35,56,17,21,92), $len =count ($array);//calculate array length for ($i =0; $i <$ len-1; $i + +) {//need to compare $len-1 wheels, each round need to compare $len-1 times for  ($j =0; $j < $len-1; $j + +) {//need to compare $len-1 times, because there are no numbers to compare when looping to the last number, So the loop to the second-to-   last number is exactly $k = $j +1;//Gets the subscript for the last number of the current number, we compare the value of the array subscript 0-1,1-2,3-4 to   if ($array [$j]> $array [$k]) {// Compare two numbers if the previous number is larger than the next, then the order of two numbers is exchanged     $t = $array [$j];     $array [$j]= $array [$k];     $array [$k]= $t;   } After the first cycle comparison, the next round of comparison  }}print_r ($array);/* The key to understanding the bubble sort is that it compares the larger number to the back, the largest number, the second largest number, the third largest number ... */?> by analogy

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.