Skip to content

Commit f4641ce

Browse files
committed
Bidirectional bubble sort
1 parent ec78042 commit f4641ce

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<?php
2+
3+
$unsorted = array(79,13,53,11,94,39,4,28,3,80);
4+
5+
/**
6+
* Swap function using a list asignment
7+
* @param $arr array
8+
* @param $idx1 int
9+
* @param $idx2 int
10+
*/
11+
function swap(array &$arr, int $idx1, int $idx2){
12+
13+
/**
14+
* Use list to assign values from a given array
15+
*/
16+
list($arr[$idx1], $arr[$idx2]) = array($arr[$idx2],$arr[$idx1]);
17+
18+
}
19+
20+
/**
21+
* Bidirecctional Bubble Sort
22+
* TODO: implement using threads
23+
*/
24+
function bi_bubble_sort(array &$unsorted) : array{
25+
26+
$swap = true;
27+
$array_count = count($unsorted) - 1;
28+
29+
do{
30+
31+
$swap = false;
32+
33+
// sort left directional
34+
for($idx = 0; $idx <= $array_count; $idx++){
35+
36+
$comp = $idx + 1;
37+
if(isset($unsorted[$comp]) && $unsorted[$idx] > $unsorted[$comp]){
38+
swap($unsorted,$idx, $comp);
39+
$swap = true;
40+
echo "swap left \n";
41+
}
42+
43+
}
44+
45+
// break if no sort
46+
if($swap == false){
47+
break;
48+
}
49+
50+
// Sort right directional
51+
for($idx = $array_count; $idx >= 0; $idx--){
52+
53+
$comp = $idx - 1;
54+
if(isset($unsorted[$comp]) && $unsorted[$idx] < $unsorted[$comp]){
55+
swap($unsorted, $idx, $comp);
56+
$swap = true;
57+
echo "swap right \n";
58+
}
59+
60+
}
61+
62+
}while($swap);
63+
64+
// return array
65+
return $unsorted;
66+
67+
}
68+
69+
// print results
70+
echo "\n";
71+
$sorted = bi_bubble_sort($unsorted);
72+
foreach($sorted as $val){
73+
echo $val, " ";
74+
}
75+
echo "\n";

0 commit comments

Comments
 (0)