Home > Backend Development > PHP Tutorial > PHP quick sort algorithm

PHP quick sort algorithm

WBOY
Release: 2016-07-25 08:43:06
Original
1026 people have browsed it
  1. function qsort(&$arr)
  2. {
  3. _quick_sort($arr, 0, count($arr) - 1);
  4. }
  5. /**
  6. * Quick sort using recursive algorithm.
  7. *
  8. * @param array $arr The array to be sorted
  9. * @param int $low The lowest sorted subsection
  10. * @param int $high The highest sorted field
  11. */
  12. function _quick_sort(&$arr, $low, $high)
  13. {
  14. $low_data = $arr[$low];
  15. $prev_low = $low;
  16. $prev_high = $high;
  17. while ($low < $high)
  18. {
  19. while ($arr[$high] >= $low_data && $low < $high) {
  20. $high--;
  21. }
  22. if ($low < $high) {
  23. $arr[$low] = $arr[$high];
  24. $low++;
  25. }
  26. while ($arr[$low] <= $low_data && $low < $high) {
  27. $low++;
  28. }
  29. if ($low < $high) {
  30. $arr[$high] = $arr[$low];
  31. $high--;
  32. }
  33. }
  34. $arr[$low] = $low_data;
  35. if ($prev_low < $low) {
  36. _quick_sort($arr, $prev_low, $low);
  37. }
  38. if ($low + 1 < $prev_high) {
  39. _quick_sort($arr, $low + 1, $prev_high);
  40. }
  41. }
  42. function quick_sort(&$arr)
  43. {
  44. $stack = array();
  45. array_push($stack, 0);
  46. array_push($stack, count($arr) -1);
  47. while (!empty($stack)) {
  48. $high = array_pop($stack);
  49. $low = array_pop($stack);
  50. $low_data = $arr[$low];
  51. $prev_low = $low;
  52. $prev_high = $high;
  53. while ($low < $high)
  54. {
  55. while ($arr[$high] >= $low_data && $low < $high) {
  56. $high--;
  57. }
  58. if ($low < $high) {
  59. $arr[$low] = $arr[$high];
  60. $low++;
  61. }
  62. while ($arr[$low] <= $low_data && $low < $high) {
  63. $low++;
  64. }
  65. if ($low < $high) {
  66. $arr[$high] = $arr[$low];
  67. $high--;
  68. }
  69. }
  70. $arr[$low] = $low_data;
  71. if ($prev_low < $low) {
  72. array_push($stack, $prev_low);
  73. array_push($stack, $low);
  74. }
  75. if ($low + 1 < $prev_high) {
  76. array_push($stack, $low + 1);
  77. array_push($stack, $prev_high);
  78. }
  79. }
  80. }
复制代码

php


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template