Re: is PHP crazy, or am I?

From: Date: Fri, 14 Sep 2001 05:07:40 +0000
Subject: Re: is PHP crazy, or am I?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-67326@lists.php.net to get a copy of this message
function bubblesort(&$vetor,$tam) { $trocou=true; $i=$j=0; while($trocou) { $trocou=false; # You set $trocou to false here, and never reset it to true # This loop will execute exactly once. for($j=0; $j<$tam-$i; $j++) { if($vetor[$j] > $vetor[$j+1]) { $aux=$vetor[$j]; $vetor[$j]=$vetor[$j+1]; $vetor[$j+1]=$aux; } $i++; } } } > it's right right? No. As near as I can figure, you are incrementing $j and decrementing $i on every iteration. That would mean that even if you fixed $trocou your sort algorithm would be O(n) (Actually it's exactly 1/2 n, but that's the same as O(n) for sufficiently large n.) Alas, that can't be correct (we wish) and is not the standard bubble sort... Try this for the body: for ($i = 0; $i < $tam -1; $i++){ for ($j = $i + 1; $j < $tam -1; $j++){ if ($vetor[$i] < $vetor[$j]){ $aux = $vetor[$i]; $vetor[$i] = $vetor[$j]; $vetor[$j] = $aux; } } } Forget the trocou bit. > so why when I print the array (with a for(;;) or with print_r) it still > shows me it's not ordered... I printed it INSIDE the function... what's the > thing here? I'm I nuts? -- WARNING richard@zend.com address is an endangered species -- Use ceo@l-i-e.com Wanna help me out? Like Music? Buy a CD: http://l-i-e.com/artists.htm Volunteer a little time: http://chatmusic.com/volunteer.htm

« previous php.general (#67326) next »