Quick sorting is achieved by continuously locating the position of the reference number
- /**
- * 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) {
-
- // Find units smaller than the base number from right to left
- while(($standard <= $this->a[$j]) && ($j > $i)) {
- $j--;
- }
-
- // Find the standard number from left to right Big
- while(($standard >= $this->a[$i]) && ($j > $i)) {
- $i++;
- }
-
- $tmp = $this->a [$i];
- $this->a[$i] = $this->a[$j];
- $this->a[$j] = $tmp;
- }
-
- // OK The position of the base number
- $this->a[$left] = $this->a[$i];
- $this->a[$i] = $standard;
-
- $this->qsort ($left, $i - 1);
- $this->qsort($i + 1, $right);
- }
-
- // Execute function
- public function main()
- {
- $left = 0;
- $right = count($this->a) - 1;
- $this->qsort($left, $right);
- print_r($this->a);
- }
- }
-
- $demo = new Demo();
- $demo->main();
Copy code
From: http://my.oschina.net/liuke1556/blog/488215 |