Home > Backend Development > PHP Tutorial > PHP array bubble sort algorithm example, PHP array algorithm example_PHP tutorial

PHP array bubble sort algorithm example, PHP array algorithm example_PHP tutorial

WBOY
Release: 2016-07-12 08:53:46
Original
1057 people have browsed it

php array bubble sorting algorithm example, php array algorithm example

The example in this article describes the php array bubble sorting algorithm. Share it with everyone for your reference, the details are as follows:

<&#63;php
/*@冒泡排序算法
*/
$array=array(5,45,22,11,32,28,35,56,17,21,92);
$len=count($array);//计算数组长度
for($i=0;$i<$len-1;$i++){//需要比较$len-1轮,每一轮需要比较$len-1次
  for($j=0;$j<$len-1;$j++){//需要比较$len-1次,因为循环到最后一个数时,后面没有数可以比较了,所以循环到倒数第二个数正好
   $k=$j+1;//得到当前数的后一个数的下标,我们依次比较的是数组下标分别为0-1,1-2,3-4的数值对
   if($array[$j]>$array[$k]){//比较两数,如果前一个数比后一个大,则交换两个数的顺序
     $t=$array[$j];
     $array[$j]=$array[$k];
     $array[$k]=$t;
   }//第一次循环比较完之后,进行下一轮比较
  }
}
print_r($array);
/*理解冒泡排序的关键在于,它的比较结果是大数往后放,依次得出的是最大的数,第二大的数,第三大的数。。。依次类推*/
&#63;>

Copy after login

Readers who are interested in more PHP-related content can check out the special topics on this site: "Complete PHP Array Operation Skills", "Summary of PHP Sorting Algorithms", "Summary of PHP Common Traversal Algorithms and Techniques", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary", "PHP Mathematical Operation Skills Summary", "php Regular Expression Usage Summary", "PHP Operations and Operator Usage Summary", "php String Usage Summary" 》and《Summary of common database operation skills in php》

I hope this article will be helpful to everyone in PHP programming.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1123797.htmlTechArticlephp array bubble sort algorithm example, php array algorithm example This article describes the php array bubble sort algorithm. Share it with everyone for your reference, the details are as follows: php/*@Bubble sort algorithm...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template