美文网首页
快速排序【一】,php实现

快速排序【一】,php实现

作者: designer | 来源:发表于2022-02-21 23:25 被阅读0次
    <?php
    /**
     * @Author: fql
     * @Email: fangqiulin4923@gmail.com
     * @Date: 2020-07-18 22:25
     */
    
    namespace fql\algorithm\sort;
    
    use Monolog\Logger;
    
    /**
     * Class QuickSort
     * @package fql\sort
     * 1、从数组选定一个元素N,作为基准元素
     * 2、遍历数组,将数组分为三部分,小于M,N,大于N
     * 3、然后按照此方法,对小于N和大于N部分进行递归,从而达到排序
     */
    class QuickSort extends Sort
    {
        protected function sort(array &$array)
        {
            $array = $this->quickSort($array);
        }
    
        //选定基准元素,并排序基准元素
        private function quickSort($array)
        {
            if (count($array) <= 1) {
                return $array;
            }
            $middle = $array[0]; // 中间值
            $left = array();
            $right = array();
            // 循环比较
            for ($i = 1; $i < count($array); $i++) {
                if ($middle < $array[$i]) {
                    // 大于中间值
                    $right[] = $array[$i];
                } else {
                    // 小于中间值
                    $left[] = $array[$i];
                }
            }
            $left = $this->quickSort($left);
            $right = $this->quickSort($right);
    
            // 合并排序后的数据,别忘了合并中间值
            return array_merge($left, array($middle), $right);
        }
    }
    
    $arr = [4, 7, 6, 3, 5, 8, 9, 10, 1, 2];
    $this->sort($arr);
    

    相关文章

      网友评论

          本文标题:快速排序【一】,php实现

          本文链接:https://www.haomeiwen.com/subject/rpywlrtx.html