Home > Article > Backend Development > Another bubble sorting algorithm implemented in PHP to share, php bubble sorting algorithm_PHP tutorial
The classic bubble sorting method has always been one of the sorting methods used by many programs. It is said that the bubble sorting method is more efficient than the PHP system function sort. This chapter does not discuss performance, so we will not compare it with system performance.
Bubble sorting roughly means comparing two adjacent numbers in sequence, and then sorting according to size until the last two digits. Since in the sorting process, small numbers are always placed forward and large numbers are placed backward, which is equivalent to bubbles rising, so it is called bubble sorting. But in fact, in the actual process, you can also use it in reverse according to your own needs. The big trees are placed forward and the decimals are placed backward.
<?php /** * PHP中的冒泡排序法使用 */ // 预先声明一个数组 $arr = array (12,45,28,30,88,67); echo "原数组"; print_r($arr); echo "<br/>"; //冒泡排序 function maopao($arr){ // 进行第一层遍历 for($i=0,$k=count($arr);$i<$k;$i++) { // 进行第二层遍历 将数组中每一个元素都与外层元素比较 // 这里的i+1意思是外层遍历当前元素往后的 for ($j=$i+1;$j<$k;$j++) { // 内外层两个数比较 if($arr[$i]<$arr[$j]){ // 先把其中一个数组赋值给临时变量 $temp = $arr[$j]; // 交换位置 $arr[$j] = $arr[$i]; // 再从临时变量中赋值回来 $arr[$i] = $temp; } } } // 返回排序后的数组 return $arr; } // 直接打印排序后的数组 echo '排序后'; print_r(maopao($arr)); ?>
Execute the results through the above code
Original array
int [] array = new int
;
int temp = 0 ;
for (int i = 0 ; i c691218ccc0a461dfd4a69ed8f11c4cd
#include 3f68df5471146346142495b14e43a419
#define M 10
using namespace std;
void maopao1(int data[M])
{
int i,j,t;
for(i=1;ica07010446304890f90d715fdb387863data[j+1])
{t=data[j];data[j]=data[j+1];data[j+1]=t;}
cout789f8754fbe986d5f90d7d14a18b517c>data[i];
maopao1(data);//from small to large
maopao2(data );//From big to small
system("pause");
return 0;
}