Log in

View Full Version : insertion sort



ggalan
10-05-2010, 02:21 AM
i am trying to write this algorithm in php but the output doesnt sort the array from small to large value like its supposed to. the algorithm is taken from a text book but my syntax might be wrong. can anyone lend a hand please



<?php
$arr = array( 4, 3, 2324, 28, 999, 821, 423, 22, 21, 2, 1 );
$j = 0;

for( $j; $j < $arr.length; $j++ )
{
$key = $arr[$j];
$i = $j - 1;

while( $i > -1 && $arr[$i] > $key )
{
$arr[$i + 1] = $arr[$i];
$i = $i - 1;
}

$arr[$i + 1] = $key;

}
print_r($arr);

?>

ggalan
10-05-2010, 02:36 AM
nm


count($arr)

ggalan
10-05-2010, 03:08 AM
why does the output look like this?


Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 21 [5] => 22 [6] => 28 [7] => 423 [8] => 821 [9] => 999 [10] => 2324 )


how can i get rid of the array index and "=>" symbol

bluewalrus
10-05-2010, 03:19 AM
The print_r does that you'll need to use a foreach loop.



<?php
$arr = array( 4, 3, 2324, 28, 999, 821, 423, 22, 21, 2, 1 );
$j = 0;

for( $j; $j < $arr.length; $j++ )
{
$key = $arr[$j];
$i = $j - 1;

while( $i > -1 && $arr[$i] > $key )
{
$arr[$i + 1] = $arr[$i];
$i = $i - 1;
}

$arr[$i + 1] = $key;

}
foreach ($arr as $value) {
echo "$value<br />\n";
}
?>

ggalan
10-05-2010, 03:24 AM
i see, thank you