>  기사  >  백엔드 개발  >  PHP一个简单的快速排序

PHP一个简单的快速排序

WBOY
WBOY원래의
2016-07-25 08:42:38784검색
通过不断的定位基准数的位置来实现快速排序
  1. /**
  2. * Created by PhpStorm.
  3. * User: saint
  4. * Date: 15/8/5
  5. * Time: 上午11:49
  6. */
  7. class Demo
  8. {
  9. public $a = array(3, 6, 9, 2, 4, 7, 1, 5, 8, 0);
  10. public function qsort($left, $right)
  11. {
  12. if($left > $right) {
  13. return;
  14. }
  15. $i = $left;
  16. $j = $right;
  17. $standard = $this->a[$left];
  18. while($i != $j) {
  19. // 从右向左查找比基准数小的单元
  20. while(($standard a[$j]) && ($j > $i)) {
  21. $j--;
  22. }
  23. // 从左到右查找比基准数大的
  24. while(($standard >= $this->a[$i]) && ($j > $i)) {
  25. $i++;
  26. }
  27. $tmp = $this->a[$i];
  28. $this->a[$i] = $this->a[$j];
  29. $this->a[$j] = $tmp;
  30. }
  31. // 确定基准数的位置
  32. $this->a[$left] = $this->a[$i];
  33. $this->a[$i] = $standard;
  34. $this->qsort($left, $i - 1);
  35. $this->qsort($i + 1, $right);
  36. }
  37. // 执行函数
  38. public function main()
  39. {
  40. $left = 0;
  41. $right = count($this->a) - 1;
  42. $this->qsort($left, $right);
  43. print_r($this->a);
  44. }
  45. }
  46. $demo = new Demo();
  47. $demo->main();
复制代码

来自:http://my.oschina.net/liuke1556/blog/488215
PHP


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.