Page 1 of 1

insertion sort

Posted: Mon Oct 04, 2010 7:54 pm
by ggalan
i am trying to write this algorithm into php but the output doesnt sort the array from small to large number 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

Code: Select all


<?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);

?>

Re: insertion sort

Posted: Mon Oct 04, 2010 9:27 pm
by requinix

Code: Select all

$j < $arr.length
That's not how you find the size of an array in PHP.

Re: insertion sort

Posted: Mon Oct 04, 2010 9:31 pm
by ggalan
ahh

Code: Select all

count($arr)