Home >Backend Development >PHP Tutorial >Examples of PHP quick sort algorithm (recursive sorting and iterative sorting)

Examples of PHP quick sort algorithm (recursive sorting and iterative sorting)

WBOY
WBOYOriginal
2016-07-25 08:51:241197browse
  1. /**
  2. * Quick sort implemented by recursive method
  3. */
  4. function quicksort($seq)
  5. {
  6. $k = $seq[0];
  7. $x = array();
  8. $y = array();
  9. for($i=1; $i< $_size; $i++) {
  10. if($seq[$i] <= $k) {
  11. $x[] = $seq[$i];
  12. } else {
  13. $y[] = $seq[$i];
  14. }
  15. }
  16. $x = quicksort($x);
  17. $y = quicksort($y);
  18. return array_merge($x, array($k), $y);
  19. } else {
  20. return $seq;
  21. }
  22. }
复制代码

2、迭代法:

  1. /**
  2. * Quick sort using iterative method
  3. */
  4. function quicksortx(&$seq)
  5. {
  6. $stack = array($seq);
  7. $sort = array();
  8. while ($stack) {
  9. $arr = array_pop($stack);
  10. if(count($arr) <= 1) {
  11. if(count($arr) == 1) {
  12. $sort[] = &$arr[0];
  13. }
  14. continue;
  15. }
  16. $k = $arr[0];
  17. $x = array();
  18. $y = array();
  19. $_size = count($arr);
  20. for($i =1 ;$i < $_size; $i++) {
  21. if($arr[$i] <= $k) {
  22. $x[] = &$arr[$i];
  23. } else {
  24. $y[] = &$arr[$i];
  25. }
  26. }
  27. !empty($y) && array_push($stack, $y);
  28. array_push($stack, array($arr[0]));
  29. !empty($x) && array_push($stack, $x);
  30. }
  31. return $sort;
  32. }
复制代码

使用:

  1. /**
  2. *Generate a random array
  3. */
  4. for($i=0;$i<5;$i++){
  5. $testArr[]=mt_rand(0,100);
  6. }
  7. var_dump($testArr);
  8. var_dump(quicksort($testArr));
  9. var_dump(quicksortx($testArr));
复制代码


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn