Examples of how PHP implements bubble sorting

Source: Internet
Author: User
Tags php code

A procedure should include:
Description of the data: in the program to specify the type of data and the organization of the data, that is, structure.
Description of the operation: the operation step, i.e. the algorithm (algorithm).
The formula proposed by Nikiklaus Wirth: program = data structure + algorithm
As a pan cut the sash North 匦 the? 闼 Jake driving? Just start with the simplest. => Bubble sort


Bubble sort (English: Bubble sort, taiwan another translation: Bubble sort) is a simple sorting algorithm. It repeatedly visits the sequence to be sorted, compares two elements at a time, and swaps them if their order is wrong. The task of visiting the series is repeated until no further exchange is needed, which means that the sequence has been sorted. The algorithm is named because the smaller elements float slowly through the exchange to the top of the sequence.

I understand bubble sort is the pupil queue, you are shorter than me (the number is small), you stand in front of me (float up), until find taller than me that, I stand in front of him, he continues to the back than the stature!
Directly on the PHP code
<?php

$arr = Array (1, 43, 54, 72, 21, 66, 32,55,11, 78, 36, 76, 39,88);
function Getpao ($arr)
{
$len = count ($arr);
Set an empty array to receive the bubbles
This layer loops the number of wheels that need to bubble
for ($i = 1; $i < $len; $i + +) {//The layer loop is used to control the number of times a number needs to be compared per round
for ($k = 0; $k < $len-$i; $k + +) {
if ($arr [$k] > $arr [$k + 1]) {
$tmp = $arr [$k + 1];
$arr [$k + 1] = $arr [$k];
$arr [$k] = $tmp;
}
}
}
return $arr;
}
Var_dump (Getpao ($arr));


Run results

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.