Sort two ways

Sort by:

  • Quick Sort

               Quick sort is very common and efficient algorithm, the idea is: first choose a scale, use it to go over the entire cohort screened to ensure its elements are not greater than its left, the right of its elements are not small and

$arr = [234,3,14,2,45,12,4567,455,343];
public function quickSort($arr){
        // 获取数组长度
        $length = count($arr);

        // 判断长度是否需要继续二分比较
        if($length <= 1){
            return $arr;
        }

        // 定义基准元素
        $base = $arr[0];

        // 定义两个空数组,用于存放和基准元素的比较后的结果
        $left = [];
        $right = [];

        // 遍历数组
        for ($i=1; $i < $length; $i++) {

            // 和基准元素作比较
            if ($arr[$i] > $base) {
                $right[] = $arr[$i];
            }else {
                $left[] = $arr[$i];
            }

        }

        // 然后递归分别处理left和right
        $left = $this->quickSort($left);
        $right = $this->quickSort($right);

        // 合并
        return array_merge($left,[$base],$right);

    }

              Returns a value of: [2,3,12,14,45,234,343,455,4567]

  • Bubble Sort

      Principle: for a set of data, comparing the size of adjacent data, the data value is small at the front, a large data value on the back.

$arr = [234,3,14,2,45,12,4567,455,343];
public function quickSort($arr){
        // 获取数组长度
        $length = count($arr);

        // 第一层循环控制冒泡轮次
        for ($i=0; $i < $length-1; $i++) {

            // 内层循环控制从第0个键值和后一个键值比较,每次冒出一个最大的数
            for ($k=0; $k < $length-1-$i; $k++) {
                if($arr[$k] > $arr[$k+1]){
                    $tmp = $arr[$k+1];
                    $arr[$k+1] = $arr[$k];
                    $arr[$k] = $tmp;
                }
            }
        }
        return $arr;
    }

 

             Returns a value of: [2,3,12,14,45,234,343,455,4567]

 

Guess you like

Origin blog.csdn.net/weixin_39616995/article/details/85989576