Today, I want to show you guys how to sort an array of integers without using PHP built-in sort function. It can be done using different sorting algorithms. Here in this post I have used Bubble Sort algorithm.
<?php
$srtArray=array(2,8,9,5,6,3,7,5,8,4,1);
for ($i=0; $i<count($srtArray); $i++) {
for ($j=0; $j<count($srtArray); $j++) {
// Compare two elements of array
if ($srtArray[$j] > $srtArray[$i]){
$tmp = $srtArray[$i];
$srtArray[$i] = $srtArray[$j];
$srtArray[$j] = $tmp;
}
}
}
//Print an array after sorting
for($i=0;$i<count($srtArray);$i++){
echo $srtArray[$i]."<br>\n";
}
?>
<?php
$srtArray=array(2,8,9,5,6,3,7,5,8,4,1);
for ($i=0; $i<count($srtArray); $i++) {
for ($j=0; $j<count($srtArray); $j++) {
// Compare two elements of array
if ($srtArray[$j] > $srtArray[$i]){
$tmp = $srtArray[$i];
$srtArray[$i] = $srtArray[$j];
$srtArray[$j] = $tmp;
}
}
}
//Print an array after sorting
for($i=0;$i<count($srtArray);$i++){
echo $srtArray[$i]."<br>\n";
}
?>
No comments:
Post a Comment