算法系列-快速排序

phpman.song@gmail.com发布

定义

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

原理

  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));
分类: 算法

20 条评论

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?

mercedes key replacement · 2021年1月5日 下午5:26

I wanted to check up and let you know how really I liked discovering your blog today.

vardenafil tablets · 2021年1月7日 上午11:12

Thanks for your whole work on this website. My niece takes pleasure in working on research and it is simple to grasp why. We all notice all relating to the powerful ways you render worthwhile tricks via your website and therefore welcome response from website visitors on this topic while our own simple princess is without question understanding so much. Take pleasure in the rest of the year. Your performing a wonderful job.

levitra pills · 2021年1月8日 上午6:05

Needed to write you this very small word to help thank you very much yet again with the unique tricks you have shown on this website. This is so wonderfully open-handed with you to supply without restraint what exactly some people would have supplied for an electronic book to make some profit on their own, specifically since you might well have tried it in the event you wanted. Those tips likewise worked to provide a great way to understand that the rest have the same zeal the same as my very own to understand way more with regards to this problem. I think there are thousands of more pleasurable times up front for those who take a look at your website.

发表评论

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