欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP一个简单的快速排序

程序员文章站 2022-05-27 21:03:28
...
通过不断的定位基准数的位置来实现快速排序
  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