Check this one , this one is more efficient
$array=array('2','4','8','5','1','7','6','9','10','3');
for($i=1;$i< count($array);$i++)
{
for($j=$i;$j>0;$j--)
{
if($array[$j] < $array[$j-1])
{
$tmp = $array[$j];
$array[$j] = $array[$j-1];
$array[$j-1] = $tmp ;
}
}
}
echo "<pre>";
print_r($array);
We can use a Bubble Sort for sorting.
The best-case performance of O(n). Otherwise, best-case == worse-case == average-case == O(n^2)
$Obj1 = array(20, 30, 10, 50, 40, 60, 100, 90, 80, 70);
$temp;
print_r($Obj1);
for ($i = 0; $i < sizeof($Obj1) - 1; $i++) {
for ($j = sizeof($Obj1) - 1; $j > $i; $j--) {
if ($Obj1[$j - 1] > $Obj1[$j]) {
$temp = $Obj1[$j-1];
$Obj1[$j-1] = $Obj1[$j];
$Obj1[$j] = $temp;
$temp = 0;
}
}
}
print_r($Obj1);
$arr = array(8, 2, 7, 4, 5);
for($j=0; $j <= count($arr)-1; $j++){
for($i=0; $i <= count($arr)-1; $i++){
if( $arr[$i] < $arr[$j]){ //'<' or '>' operator for Asc, Dec.
$temp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $temp;
}
}
echo'<pre>';
print_r($arr);
Sorting array value without using built in php like sort() etc show demo Only for php7.2.0 - 7.4.4
<?php
$str = [54,23,2,56,7,2,300];
$count = count($str);
for ($j = 0; $j < $count; $j++) {
for ($i = $j + 1; $i < $count; $i++) {
if ($str[$i] < $str[$j]) {
list($str[$i], $str[$j]) = [$str[$j], $str[$i]];
}
}
}
print_r($str);
?>
Here is the way of sorting.
<?php
$array=array('2','4','8','5','1','7','6','9','10','3');
echo "Unsorted array is: ";
echo "<br />";
print_r($array);
for($j = 0; $j < count($array); $j ++) {
for($i = 0; $i < count($array)-1; $i ++){
if($array[$i] > $array[$i+1]) {
$temp = $array[$i+1];
$array[$i+1]=$array[$i];
$array[$i]=$temp;
}
}
}
echo "Sorted Array is: ";
echo "<br />";
print_r($array);
?>
**Using Bubbole Sort:**
<?php
$arr =array(12,10,190,90,890);
echo "Before Sorting Array";echo '</br>';
print_r($arr);echo '</br>';
echo 'After Sorting Arry:'.'</br>';
for ($i = 0; $i < sizeof($arr); $i++) {
for ($j = $i + 1; $j < sizeof($arr); $j++) {
$tmp = 0;
if ($arr[$i] > $arr[$j]) {
$tmp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $tmp;
}
}
echo $arr[$i];echo '</br>';
}
?>