A brief discussion on php bubble sorting, a brief discussion on php bubble sorting_PHP tutorial

WBOY
Release: 2016-07-13 10:10:28
Original
972 people have browsed it

A brief talk about php bubble sorting, a brief talk about php bubble sorting

The PHP implementation code is presented first:

Copy code The code is as follows:

function bubble_sort($array) {
for ($i = 0; $i < count($array) - 1; $i++) { //$i is the number of sorted elements
for ($j = 0; $j < count($array) - 1 - $i; $j++) { //$j is the number of elements to be sorted, subtract $i
from the total length If ($array[$j] > $array[$j + 1]) { //Sort in ascending order
                     $temp = $array[$j];
$array[$j] = $array[$j + 1];
$array[$j + 1] = $temp;
            }
}
}
Return $array;
}

$a = array(5, 1, 4, 7);

Code execution process:

Copy code The code is as follows:

i = 0;
j = 0;
if($arr[0] > $arr[1]) => 5 > 1 If the condition is true, swap positions to form a new array => 1 5 4 7 j++
if($arr[1] > $arr[2]) => 5 > 4 If the condition is true, swap positions to form a new array => 1 4 5 7 j++
if($arr[2] > $arr[3]) => 5 > 7 The condition is not established, the array remains unchanged, 1 4 5 7 j++ j=3 Exit the inner loop, i++

Let’s follow this example in turn.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/935491.htmlTechArticleA brief discussion of php bubble sorting, a brief discussion of php bubble PHP implementation code is presented first: Copy the code as follows : function bubble_sort($array) { for ($i = 0; $i count($array) - 1; $i++) { //$i is...
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!