The idea and code implementation of php array bubble sort

Table of contents

 

Sort ideas:

Code:

1. Sort in ascending order (from small to large)

Basic code:

 final effect:

 

2. Sort in descending order (from largest to smallest)

Basic code:

 final effect:

Summarize:


Sort ideas:

In the process of bubble sorting, the values ​​of two adjacent elements in the array are continuously compared according to the sorting order from small to large or from large to small, and the smaller or larger element is moved forward. Finally implement bubble sort.

Code:

1. Sort in ascending order (from small to large)

Sort the array [  78,2,27,5,34,31,98,45 ] in ascending order (from small to large)

Basic code:

<?php

//申明数组
$array = [78,2,27,5,34,31,98,45];

//申明函数
function bubble($arr){
    //外层循环控制需要比较的轮数(控制比较的轮数)
    for($i=1;$i<count($arr);$i++){
        //内层循环参与比较的元素
        for($j=0;$j<count($arr)-1;$j++){
            //比较相邻的两个元素
            if($arr[$j] > $arr[$j+1]){
                $temp = $arr[$j];
                $arr[$j] = $arr[$j+1];
                $arr[$j+1] = $temp;
            }
        }
    }

    return $arr;
}

//调用函数,并输出
echo "<pre>";
print_r(bubble($array));

 final effect:

 

2. Sort in descending order (from largest to smallest)

Sort the array [  78,2,27,5,34,31,98,45 ] in ascending order (from large to small)

Basic code:

<?php

//申明数组
$array = [78,2,27,5,34,31,98,45];

//申明函数
function bubble($arr){
    //外层循环控制需要比较的轮数(控制比较的轮数)
    for($i=1;$i<count($arr);$i++){
        //内层循环参与比较的元素
        for($j=0;$j<count($arr)-1;$j++){
            //比较相邻的两个元素
            if($arr[$j] < $arr[$j+1]){
                $temp = $arr[$j];
                $arr[$j] = $arr[$j+1];
                $arr[$j+1] = $temp;
            }
        }
    }

    return $arr;
}

//调用函数,并输出
echo "<pre>";
print_r(bubble($array));

 final effect:

 

 

Summarize:

The key to sorting in ascending and descending order is to compare adjacent two elements, "<" ">"

ascending order:

descending order:

 

     If there are similarities and differences in the test, you can leave a message to solve it together

 

Guess you like

Origin blog.csdn.net/qq_43269730/article/details/89182408