其实快速排序之所以称之快速,就是因为,冒泡排序是每次对比只交换相邻的两个值的位置,这样每个值要移动到它最终的排序结果中所对应的位置,可能需要很多次位置
概念
这里借用百度百科的一张图来,非常形象:
快速排序算法是对冒泡算法的一个优化。他的思想是先对数组进行分割, 把大的元素数值放到一个临时数组里,把小的元素数值放到另一个临时数组里(这个分割的点可以是数组中的任意一个元素值,一般用第一个元素,即$array[0]),然后继续把这两个临时数组重复上面拆分,最后把小的数组元素和大的数组元素合并起来。这里用到了递归的思想。
PHP实现
复制代码 代码如下:
/*
快速排序
*/
function quickSort($array)
{
if(!isset($array[1]))
return $array;
$mid = $array[0]; //获取一个用于分割的关键字,一般是首个元素
$leftArray = array();
$rightArray = array();
foreach($array as $v)
{
if($v > $mid)
$rightArray[] = $v; //把比$mid大的数放到一个数组里
if($v
$leftArray[] = $v; //把比$mid小的数放到另一个数组里
}
$leftArray = quickSort($leftArray); //把比较小的数组再一次进行分割
$leftArray[] = $mid; //把分割的元素加到小的数组后面,不能忘了它哦
$rightArray = quickSort($rightArray); //把比较大的数组再一次进行分割
return array_merge($leftArray,$rightArray); //组合两个结果
}
与冒泡算法对比
这里我与之前写的冒泡算法实现的排序做了个对比,,可以看出这个算法比冒泡算法的效率要高很多。
复制代码 代码如下:
$a = array_rand(range(1,3000), 1500); //甚至在冒泡算法超过1600个元素的时候会出现内存不足的提示,但这里为了测出两个之间的差别大小, 就设置成了1500,保证冒泡算法也能执行完毕。
shuffle($a); //获取已经打乱了顺序的数组
$t1 = microtime(true);
quickSort($a); //快速排序
$t2 = microtime(true);
echo (($t2-$t1)*1000).'ms
';
require('./maopao.php'); //这里引用的是我之前写的冒泡算法排序
$t1 = microtime(true);
maoPao($a); //冒泡
$t2 = microtime(true);
echo (($t2-$t1)*1000).'ms';
运行结果:
复制代码 代码如下:
12.10880279541ms
772.64094352722ms

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment
