quick sort 快速排序算法

2016-09-08 • PHP1 Comment

class QuickSort{

    public $sequence;

    public function init($sequence){

        if (!is_array($sequence))
            return false;

        $this->sequence = $sequence;
        $this->partition(0, len($sequence) - 1);

        sprintf("Enter : %s\n", implode(',', $sequence));
        sprintf("Result : %s\n", implode(',', $this->sequence));
    }
    public function partition($i, $j){

        $point = $this->sequence[$i];
        $left = $this->sequence[$i+1];
        $right = $this->sequence[$j]
        $begin = $i;
        $end = $j;

        while ($i != $j) {
            
            while ($right >= $point && $i != $j)
                $right = $this->sequence[$j--];

            while($left <= $point && $i != $j)
                $left = $this->sequence[$i++];

            $this->exchange($i, $j);
        }

        $this->exchange($begin, $i);

        $this->partition($begin, $i - 1);
        $this->partition($i + 1, $end);
    }

    public function exchange($a, $b){
        $tmp = $this->sequence[$a];
        $this->sequence[$a] = $this->sequence[$b];
        $this->sequence[$b] = $tmp;

        return true;
    }    

}

$qs = new QuickSort();
$qs->init(array(4, 3, 7, 6, 1, 5, 2));

仅有一条评论
  1. 秋刀鱼 秋刀鱼

    没写过php,话说不能调库的么

粤公网安备 44011102000950号