I need to do a bubble sort algorithm in PHP.
I want to know whether any one has any good examples that I can use, or an open source library which can do this.
I have a few spaces in a set (array), i want to fill these spaces with object (a person), so no space can have a male and a female, this why i am trying to find out a bubble sort algorithm.
My plan is to fill in any of the available spaces regardless of the gender, and after that sort them separately.
Thanks.
Write a PHP program to sort a list of elements using Bubble sort. According to Wikipedia "Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated ...
Bubble Sort. Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Worst case occurs when array is reverse sorted. Best Case Time Complexity: O (n). Best case occurs when array is already sorted. Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted. Due to its simplicity, bubble sort is often used to introduce the concept of a sorting algorithm.
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. Example: First Pass: ( 514 2 8 ) –> ( 154 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
function bubble_sort($arr) {
$size = count($arr)-1;
for ($i=0; $i<$size; $i++) {
for ($j=0; $j<$size-$i; $j++) {
$k = $j+1;
if ($arr[$k] < $arr[$j]) {
// Swap elements at indices: $j, $k
list($arr[$j], $arr[$k]) = array($arr[$k], $arr[$j]);
}
}
}
return $arr;
}
For example:
$arr = array(1,3,2,8,5,7,4,0);
print("Before sorting");
print_r($arr);
$arr = bubble_sort($arr);
print("After sorting by using bubble sort");
print_r($arr);
Using bubble sort is a very bad idea. It has complexity of O(n^2)
.
You should use php usort, which is actually a merge sort implementation and guaranteed O(n*log(n))
complexity.
A sample code from the PHP Manual -
function cmp( $a, $b ) {
if( $a->weight == $b->weight ){ return 0 ; }
return ($a->weight < $b->weight) ? -1 : 1;
}
usort($unsortedObjectArray,'cmp');
$numbers = array(1,3,2,5,2);
$array_size = count($numbers);
echo "Numbers before sort: ";
for ( $i = 0; $i < $array_size; $i++ )
echo $numbers[$i];
echo "n";
for ( $i = 0; $i < $array_size; $i++ )
{
for ($j = 0; $j < $array_size; $j++ )
{
if ($numbers[$i] < $numbers[$j])
{
$temp = $numbers[$i];
$numbers[$i] = $numbers[$j];
$numbers[$j] = $temp;
}
}
}
echo "Numbers after sort: ";
for( $i = 0; $i < $array_size; $i++ )
echo $numbers[$i];
echo "n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With