Version: 3.0

Type: Function

Category: Algorithms

License: Other

Description: This is a simple bubblesort by Petter Nilsenthat takes 2 arrays as argument.The first one is the actual data used for sorting, the second is data that will "tag along" with the first array, for instance a descriptive text about the data in the first array.



/* Author: J.B.Lamer, Date: 20070321
 *
 * bubblesort() takes one array and sorts it
 * slow but simple
 *
 * If you want to reverse, suggest doing the
 *  check outside of the for loops
 *  and call two different (outer) for loops
 *  checking on each rotation can slow you down
 */
function bubblesort( &$a1 )
{
	if ( !is_array($a1) )
	{ return false; }
	$len = count($a1);
	// go down array and get an element
	for( $i = 0; $i < $len; $i++ )
	{
		// check everything above element
		// if we are larger than swap it
		// with that one
		for ( $j = ($i+1); $j < $len; $j++ )
		{
			if ( $a1[$i] > $a1[$j] )
			{	swap( $a1[$i], $a1[$j] ); }
		}
		// at this point the position at $i is the smallest
		// go to the next one
	}
	return true;
}

if ( !function_exists('swap') )
{
	// quess what this function is for
	function swap( &$a, &$b )
	{
		$h = $a;
		$a = $b;
		$b = $h;
	}
}