insertion sort

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ggalan
Forum Newbie
Posts: 8
Joined: Fri Oct 01, 2010 11:54 am

insertion sort

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

?>
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: insertion sort

Post by requinix »

Code: Select all

$j < $arr.length
That's not how you find the size of an array in PHP.
ggalan
Forum Newbie
Posts: 8
Joined: Fri Oct 01, 2010 11:54 am

Re: insertion sort

Post by ggalan »

ahh

Code: Select all

count($arr)
Post Reply