Skip to content

Commit ec78042

Browse files
committed
Bubble sort simpple algo
1 parent 791c4d6 commit ec78042

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<?php
2+
3+
$unsorted = array(79,13,53,11,94,39,4,28,3,80);
4+
5+
/**
6+
* Swap function using list assingment
7+
*/
8+
function swap(array &$to_sort, $idx1, $idx2){
9+
10+
/**
11+
* Using list to make assignment from constructed array
12+
*/
13+
list($to_sort[$idx1],$to_sort[$idx2]) = array($to_sort[$idx2], $to_sort[$idx1]);
14+
}
15+
16+
/**
17+
* Sorting function using a do while
18+
*/
19+
function bubble_sort(array &$unsorted): array{
20+
21+
// swap idx
22+
$swap = true;
23+
do{
24+
25+
$swap = false;
26+
// sort
27+
foreach($unsorted as $idx => $val){
28+
29+
if(isset($unsorted[$idx + 1]) && $unsorted[$idx] > $unsorted[$idx + 1]){
30+
// swap
31+
swap($unsorted, $idx, $idx + 1);
32+
$swap = true;
33+
}
34+
35+
}
36+
37+
}while($swap);
38+
39+
return $unsorted;
40+
41+
}
42+
43+
44+
$sorted = bubble_sort($unsorted);
45+
46+
// print list
47+
echo "\n";
48+
foreach( $sorted as $val){
49+
echo $val," ";
50+
}
51+
echo "\n";

0 commit comments

Comments
 (0)