定义

快速排序是用来排列一连串数字的算法

原理

  1. 从数列中挑出一个元素,称为基准
  2. 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以放在任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区操作
  3. 递归的把小于基准值元素的子数列和大于基准元素的子数列排序

PHP实现

PHP沙盒环境

function quickSort($arr)
{
    if (count($arr) <= 1)
        return $arr;
    $middle = $arr[0];
    $leftArray = [];
    $rightArray = [];

    for ($i = 1; $i < count($arr); $i++) {
        if ($arr[$i] > $middle)
            $rightArray[] = $arr[$i];
        else
            $leftArray[] = $arr[$i];
    }
    $leftArray = quickSort($leftArray);
    $leftArray[] = $middle;

    $rightArray = quickSort($rightArray);
    return array_merge($leftArray, $rightArray);
}
//例子
$numbers = [1,3,4,22,88,33,31,42];
print_r(quickSort($numbers));
分类: 算法

7 条评论

Greggboors · 2019年10月15日 上午10:04

Хорошая статья

Jamessic · 2020年4月26日 下午11:06

You’ve wonderful stuff right here.

web hosting companies · 2020年8月8日 上午5:16

I feel that is among the so much significant info for me.

And i’m happy studying your article. However wanna commentary on some common issues, The web site style is perfect, the articles is actually
excellent : D. Just right process, cheers

web hosting services · 2020年8月8日 上午10:34

Great article! We will be linking to this great content on our site.
Keep up the good writing.

adreamoftrains best web hosting company · 2020年8月8日 下午12:12

My spouse and I stumbled over here from a different page and thought I might as well
check things out. I like what I see so now i am following
you. Look forward to looking at your web page repeatedly.
adreamoftrains web hosting companies

best web hosting 2020 · 2020年8月8日 下午7:48

Hi, the whole thing is going fine here and ofcourse every
one is sharing data, that’s in fact fine, keep up writing.

web hosting companies · 2020年8月8日 下午8:29

Tremendous things here. I’m very glad to look your
article. Thank you a lot and I’m taking a
look ahead to touch you. Will you kindly drop me
a e-mail?

发表评论

电子邮件地址不会被公开。 必填项已用*标注