-
Notifications
You must be signed in to change notification settings - Fork 5
/
BubbleSort.php
40 lines (34 loc) · 1.02 KB
/
BubbleSort.php
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
30
31
32
33
34
35
36
37
38
39
40
<?php
/*
An implementation of Bubble Sort on an array of integers.
*/
function BubbleSort($array){
if(isset($array) && is_array($array)) {/* If $array is set */
$array_length = count($array);
do{
$swapped = false;
for($i = 1; $i < $array_length; $i++) {
/* Is the number to the left of this number larger?... */
if ($array[$i-1] > $array[$i]) {
/* Yes - so swap them */
$larger=$array[$i-1];
$array[$i-1]=$array[$i];
$array[$i]=$larger;
$swapped = true;
}
}
}while($swapped == true);
return $array;
}
// $array not set issue message and end program
die("No Array! Use: BubbleSort(ARRAY)");
}
$sorted = BubbleSort(array(9,8,7,6,5,1,4,3,2,0));
var_dump($sorted);
echo '<br>' . PHP_EOL;
for($i = 0; $i <= 9; $i++){
if ($sorted[$i] == $i) {
echo "$i is correct<br>" . PHP_EOL;
}
}
?>