Tuesday, February 27, 2007

Bubble Sort - How it works

//
function BubbleSort( $items ) {
$temp = "";
$size = count( $items );
for( $i = 0; $i < $size-1; $i++ ) {
for( $j = 0; $j < $size - 1 - $i; $j++ ) {
if( $items[$j+1] < $items[$j] ) {
$temp = $items[$j];
$items[$j] = $items[$j+1];
$items[$j+1] = $temp;
}
}
}
}
//
In order to sort an array of n items, we can use this Bubble Sort Algorithm.
How it works: It's a function, that you call it and place in it, as a value.. ...the array of the items you want to sort. IT compares 2 elements. IF the first one is greater then the second one, it swaps them. And this thing is done with all of the elements, from the first 2...until the last 2. The step keeps being repeated for 1 fewer elements each time. So...basically, the step is being done until there are no more pairs to compare. As you can see, there are 2 FOR statements one inside the other. 2 Loops, one included in the other. It's a simple, but very known and used algorithm. to use it: for example you have an array of 5:
$x[0]=1;
$x[1]=6;
$x[2]=4;
$x[3]=2;
$x[4]=5;

$new_array = BubbleSort($x);

now, the content of the new array will be:
$new_array[0];//1
$new_array[1];//2
$new_array[2];//4
$new_array[3];//5
$new_array[4];//6

1 comment:

tendrel said...

I don't post nearly as often as you =), so for me 2posts/1day is an anomaly. No one comments on my blog really, because I rarely link to anyone or comment anywhere and haven't told RL people where it is.