Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.08 KB | None | 0 0
  1. //napisać algorytm o złożoności obliczeniowej n sortujący rosnąco n-elementową tablicę
  2. //https://en.wikipedia.org/wiki/Sorting_algorithm
  3. //Simple pancake sort
  4.  
  5. <?php
  6.  
  7. function pancakeSort(&$arr)
  8. {
  9.     $currentSize = count($arr);
  10.     for ($currentSize; $currentSize > 1; --$currentSize) {
  11.         $maxIndex = findMaxIndex($arr, $currentSize);
  12.        
  13.         if ($maxIndex != $currentSize - 1) {
  14.             flip($arr, $maxIndex);
  15.             flip($arr, $currentSize - 1);
  16.         }
  17.     }
  18. }
  19.  
  20. function findMaxIndex($arr, $currentSize)
  21. {
  22.     $maxIndex = 0;
  23.     for ($i = 0; $i < $currentSize; ++$i) {
  24.         if ($arr[$i] > $arr[$maxIndex]) {
  25.             $maxIndex = $i;      
  26.         }
  27.     }
  28.  
  29.     return $maxIndex;
  30. }
  31.  
  32. function flip(&$arr, $i)
  33. {
  34.     $start = 0;
  35.     while ($start < $i) {
  36.         $temp = $arr[$start];
  37.         $arr[$start] = $arr[$i];
  38.         $arr[$i] = $temp;
  39.         $start++;
  40.         $i--;
  41.     }
  42. }
  43.  
  44. $exampleArr = array(77, 6.5, 20, 11, 4.4, 21, 7);
  45.  
  46. pancakeSort($exampleArr);
  47.  
  48. var_dump($exampleArr);
  49.  
  50. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement