Blogger Information
Blog 8
fans 0
comment 0
visits 5807
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
冒泡排序与快速排序
柯二南的博客
Original
599 people have browsed it
<?php
class ArraySort{
    /*
     * author:wency;
     * name:initRand
     * purpose:快速产生一组随机数
     * @parameter  $length  长度
     * @parameter $low  int  最小数
     * @parameter $high  int 最大数
     * return:$X array
     */

    public function initRand($length, $low, $high) {

        for ($i = 0; $i < $length; $i++) {
            $arrX[] = rand($low, $high);
        }
        $X = $arrX;
        echo '<pre>';
        return ($X);
    }

    /*
     * author:wency;
     * name:bubble_sort
     * purpose:冒泡排序
     * @parameter  $X array
     * return:$X array
     */

    public function bubble_sort(&$X) {
        $count = count($X);
        for ($j = 0; $j < $count; $j++) {
            for ($i = 0; $i < $count - $j - 1; $i++) {
                if ($X[$i] > $X[$i + 1]) {
                    $temp = $X[$i];
                    $X[$i] = $X[$i + 1];
                    $X[$i + 1] = $temp;
                }
            }
        }
        return $X;
    }

    /*
     * author:wency;
     * name:quick_sort
     * purpose:快速排序
     * @parameter  $array array
     * return:$array array
     */

    public function quick_sort($array) {
        if (count($array) <= 1) {
            return $array;
        }
        $key = $array[0];
        $left = [];
        $right = [];
        for ($i = 1; $i < count($array); $i++) {
            if ($array[$i] < $key) {
                $left[] = $array[$i];
            } else {
                $right[] = $array[$i];
            }
        }
        $left = $this->quick_sort($left);
        $right = $this->quick_sort($right);
        return array_merge($left, array($key), $right);
    }

}
$obj = new ArraySort;
$newArray = $obj->initRand(20, 1, 100);
echo '<pre>';
print_r($newArray);
echo '<pre>';
//$arrX = $obj->bubble_sort($newArray);
$arrX = $obj->quick_sort($newArray);
print_r($arrX);

可以先调用类中的initRand()方法快速产生一组随机数组,再调用两个排序方法bubble_sort()和quick_sort()进行排序

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post