PHP中如何实现一个高效的快速排序算法?
- 内容介绍
- 相关推荐
本文共计312个文字,预计阅读时间需要2分钟。
使用快速排序算法实现数组快速排序,代码如下:
phpclass Demo { public $a=array(3, 6, 9, 2, 4, 7, 1, 5, 8, 0);
public function qsort($left, $right) { if ($left a[$left]; while ($i < $j) { while ($i a[$j] >=$key) { $j--; } if ($i a[$i]=$this->a[$j]; } while ($i a[$i] <=$key) { $i++; } if ($i a[$j]=$this->a[$i]; } } $this->a[$i]=$key; $this->qsort($left, $i - 1); $this->qsort($i + 1, $right); } }}
<?php /** * Created by PhpStorm. * User: saint * Date: 15/8/5 * Time: 上午11:49 */ class Demo { public $a = array(3, 6, 9, 2, 4, 7, 1, 5, 8, 0); public function qsort($left, $right) { if($left > $right) { return; } $i = $left; $j = $right; $standard = $this->a[$left]; while($i != $j) { // 从右向左查找比基准数小的单元 while(($standard <= $this->a[$j]) && ($j > $i)) { $j--; } // 从左到右查找比基准数大的 while(($standard >= $this->a[$i]) && ($j > $i)) { $i++; } $tmp = $this->a[$i]; $this->a[$i] = $this->a[$j]; $this->a[$j] = $tmp; } // 确定基准数的位置 $this->a[$left] = $this->a[$i]; $this->a[$i] = $standard; $this->qsort($left, $i - 1); $this->qsort($i + 1, $right); } // 执行函数 public function main() { $left = 0; $right = count($this->a) - 1; $this->qsort($left, $right); print_r($this->a); } } $demo = new Demo(); $demo->main(); 来自:my.oschina.net/liuke1556/blog/488215
本文共计312个文字,预计阅读时间需要2分钟。
使用快速排序算法实现数组快速排序,代码如下:
phpclass Demo { public $a=array(3, 6, 9, 2, 4, 7, 1, 5, 8, 0);
public function qsort($left, $right) { if ($left a[$left]; while ($i < $j) { while ($i a[$j] >=$key) { $j--; } if ($i a[$i]=$this->a[$j]; } while ($i a[$i] <=$key) { $i++; } if ($i a[$j]=$this->a[$i]; } } $this->a[$i]=$key; $this->qsort($left, $i - 1); $this->qsort($i + 1, $right); } }}
<?php /** * Created by PhpStorm. * User: saint * Date: 15/8/5 * Time: 上午11:49 */ class Demo { public $a = array(3, 6, 9, 2, 4, 7, 1, 5, 8, 0); public function qsort($left, $right) { if($left > $right) { return; } $i = $left; $j = $right; $standard = $this->a[$left]; while($i != $j) { // 从右向左查找比基准数小的单元 while(($standard <= $this->a[$j]) && ($j > $i)) { $j--; } // 从左到右查找比基准数大的 while(($standard >= $this->a[$i]) && ($j > $i)) { $i++; } $tmp = $this->a[$i]; $this->a[$i] = $this->a[$j]; $this->a[$j] = $tmp; } // 确定基准数的位置 $this->a[$left] = $this->a[$i]; $this->a[$i] = $standard; $this->qsort($left, $i - 1); $this->qsort($i + 1, $right); } // 执行函数 public function main() { $left = 0; $right = count($this->a) - 1; $this->qsort($left, $right); print_r($this->a); } } $demo = new Demo(); $demo->main(); 来自:my.oschina.net/liuke1556/blog/488215

