search
Homephp教程php手册排序算法之冒泡算法

排序算法之冒泡算法

Jun 13, 2016 am 10:58 AM
elementbubblesortyesCompareofSimplealgorithmwant

冒泡算法是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。

 


function BubbleSort($array){

    if (empty($array) || !is_array($array))

        return false;
    $len = count($array)-1;
    for($i = $len; $i > 0; $i-- ){
        for($j = 0; $j             if($array[$j+1]                 $temp = $array[$j];
                $array[$j] = $array[$j+1];
                $array[$j+1] = $temp;
            }
        }
    }
    return $array;
}

 

 

时间复杂度:O(n*n)

 


冒泡算法改进方法一:

如果某一次循环中没有发生任何的交换,说明数据已经排好序了,直接跳出程序。

function BubbleSort2($array)
{


    if (empty($array) || !is_array($array))

    return false;


    $len = count($array);
    $ischange = false;
    for($i = $len - 1 ;$i>0&&!$ischange;$i--)
    {
        $ischange = true;
        for($j=0; $j         {
            if($array[$j+1]             {
                $temp = $array[$j];
                $array[$j] = $array[$j + 1];
                $array[$j + 1] = $temp;
                $ischange=false;
            }
        }
    }
    return $array;
}

 

 

 

 

 

 

 

Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool