Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Factorial
  5. */
  6. function factorial($number)
  7. {
  8. static $i = 0;
  9. static $internalNumber = null;
  10.  
  11. if ($internalNumber === null) {
  12. $internalNumber = $number;
  13. }
  14.  
  15. $i++;
  16.  
  17. if ($i < $internalNumber) {
  18. return factorial($number * ($internalNumber - $i));
  19. }
  20.  
  21. $i = 0;
  22. $internalNumber = null;
  23.  
  24. return $number;
  25. }
  26.  
  27. echo PHP_EOL;
  28. var_export(factorial(6)); // 720
  29. echo PHP_EOL;
  30.  
  31.  
  32. /**
  33. * Bubble sort
  34. */
  35. $array = [3, 4, 5, 1, 2];
  36.  
  37. do {
  38. $continue = false;
  39.  
  40. for ($i = 0; $i < count($array) -1; $i++) {
  41. if ($array[$i] > $array[$i + 1]) {
  42. $temp = $array[$i + 1];
  43.  
  44. $array[$i + 1] = $array[$i];
  45. $array[$i] = $temp;
  46.  
  47. $continue = true;
  48. }
  49. }
  50. } while ($continue);
  51.  
  52. echo PHP_EOL;
  53. echo implode(', ', $array); // 1, 2, 3, 4, 5
  54. echo PHP_EOL;
  55.  
  56. /**
  57. * Bubble sort reversed (or stone sort)
  58. */
  59. $array = [1, 2, 5, 4, 3];
  60.  
  61. do {
  62. $continue = false;
  63.  
  64. for ($i = count($array) - 1; $i > 0; $i--) {
  65. if ($array[$i - 1] < $array[$i]) {
  66. $temp = $array[$i - 1];
  67.  
  68. $array[$i - 1] = $array[$i];
  69. $array[$i] = $temp;
  70.  
  71. $continue = true;
  72. }
  73. }
  74. } while ($continue);
  75.  
  76. echo PHP_EOL;
  77. echo implode(', ', $array); // 5, 4, 3, 2, 1
  78. echo PHP_EOL;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement