PHP Bubble Sort

One of an occasional series of posts on PHP algorithms. I found this originally at United Scripters, and bookmarked it for some reason.

Code

function bubbleSort($array=array()/*could have been a pointer*/){
$lastIndex=sizeof($array)-1;
while(true){
$newStartIndex=false;
$newLastIndex=0;
for($j=($startIndex)?$startIndex:1; $j<=$lastIndex; $j++){
if( $array[$j-1] > $array[$j] ){/*SWAP:*/
$temp=$array[$j-1];
$array[$j-1]=$array[$j];
$array[$j]=$temp;
if($newStartIndex===false){$newStartIndex=$j-1;};
$newLastIndex=$j-1;
};
}
if($newStartIndex===false){return $array;};
$startIndex=$newStartIndex;
$lastIndex=$newLastIndex;
}
/* keep this comment to reuse freely:
Orwant, Hietaniemi, Macdonald algorithm as Php implemented by:
http://www.unitedscripters.com */
}

Leave a Comment