Algorithm-Quick Sort (implemented by PHP code)

Quick sort principle

Be lazy, just refer to the following article for the principle. I only write the php implementation method here. Simply put, select a benchmark element to compare with the entire data. Place the smaller element on the left and the larger element on the right. Then recursively sort the left and right elements.
Portal: https://www.sohu.com/a/246785807_684445

PHP code implementation

    /**
     * 快速排序
     * @param $arr
     * @return mixed
     */
    public function quickSort($arr)
    {
    
    
        $length = count($arr);

        // 当数组只剩一个元素的时候不再迭代排序
        if ($length<=1) {
    
    
            return $arr;
        }

        // 循环数组跟基准数据作比较,比基础数据小的放左边,大的放右边
        $first = $arr[0]; //选出一个标准数据,一般选第一个或者最后一个
        $left = array(); //比标准数据小的元素放标准数据左边
        $right = array(); //比标准数据大的元素放标准数据右边
        for ($i=1;$i<$length;$i++) {
    
    
            if ($arr[$i] < $first) {
    
    
                $left[] = $arr[$i];
            } else {
    
    
                $right[] = $arr[$i];
            }
        }

        $left = $this->quickSort($left);// 递归左边数组排序
        $right = $this->quickSort($right);// 递归右边数组排序

        return array_merge($left, array($first), $right);// 合并左边数据,基准数据,右边数据
    }

Guess you like

Origin blog.csdn.net/magentodaddy/article/details/108618367