search
Homephp教程php手册如何用PHP实现插入排序?

如何用PHP实现插入排序?

Jun 13, 2016 am 11:54 AM
phpBasic operationsaccomplishsequencesortinsertdataof

插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据。

算法描述:

⒈ 从第一个元素开始,该元素可以认为已经被排序

⒉ 取出下一个元素,在已经排序的元素序列中从后向前扫描

⒊ 如果该元素(已排序)大于新元素,将该元素移到下一位置

⒋ 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置

⒌ 将新元素插入到下一位置中

⒍ 重复步骤2

复制代码 代码如下:


$arr =array(123,0,5,-1,4,15);

function insertSort(&$arr){

//先默认第一个下标为0的数是排好的数
for($i=1;$i//确定插入比较的数
$insertVal=$arr[$i];
//确定与前面比较的数比较
$insertIndex=$i-1;

//表示没有找到位置
while($insertIndex>=0 && $insertVal

//把数后移
$arr[$insertIndex+1]=$arr[$insertIndex];
$insertIndex--;
}

//插入(给$insertval找到位置了)
$arr[$insertIndex+1] = $insertVal;
}
}

insertSort($arr);
print_r($arr);
?>

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools