-
-
Notifications
You must be signed in to change notification settings - Fork 566
Expand file tree
/
Copy pathBubbleSort2.php
More file actions
29 lines (26 loc) · 680 Bytes
/
BubbleSort2.php
File metadata and controls
29 lines (26 loc) · 680 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
/*
* Bubble Sort
*
* Compare numbers in an array 2 at a time and switch them if the second number is smaller
*
* @param array $input array of random numbers
* @return array sorted array of numbers
*/
function bubbleSort2(array $input)
{
// Return nothing if input is empty
if (!isset($input)) {
return [];
}
do {
$swapped = false;
for ($i = 0, $count = sizeof($input) - 1; $i < $count; $i++) {
if ($input[$i + 1] < $input[$i]) {
list($input[$i + 1], $input[$i]) = [$input[$i], $input[$i + 1]];
$swapped = true;
}
}
} while ($swapped);
return $input;
}