Advertisement
Guest User

bubbleSorting

a guest
Feb 18th, 2018
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.06 KB | None | 0 0
  1. print_r($unsorted);
  2. $sorted = bubbleSorting1($unsorted);
  3. print_r($sorted);
  4.  
  5. function bubbleSorting($data)
  6. {
  7.     $array_length = count($data);
  8.     $iterations_count = $array_length - 1;
  9.  
  10.     //обходим массив столько раз, сколько в нём элементов
  11.     $i = 0;
  12.     while($i < $array_length) {
  13.         $sorted = FALSE;
  14.         $y = 0;
  15.         while ($y < $iterations_count) {
  16.             //сравниваем соседние элементы массива
  17.             if ($data[$y] > $data[$y + 1]) {
  18.                 $sorted = TRUE;
  19.                 //меняем их местами
  20.                 list($data[$y], $data[$y + 1]) = [
  21.                     $data[$y + 1],
  22.                     $data[$y]
  23.                 ];
  24.             }
  25.             $y++;
  26.         }
  27.         $iterations_count--;
  28.         if (!$sorted) {
  29.             //элементы не менялись местами, значит массив отсортирован
  30.             return $data;
  31.         }
  32.         $i++;
  33.     }
  34.     return $data;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement