Friday, November 9, 2007

PHP Selection sort

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has Θ(n2) complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations. It works as follows:

1. Find the minimum value in the list
2. Swap it with the value in the first position
3. Repeat the steps above for remainder of the list (starting at the second position)


Effectively, we divide the list into two parts: the sublist of items already sorted, which we build up from left to right and is found at the beginning, and the sublist of items remaining to be sorted, occupying the remainder of the array.


PHP implementation:


function straightSelection( $array )
{

for( $i=0; $i < count($array); $i ++ )
{
$k = $i;
$tmp = $array[$i];

// search elements right to current for the smallest
for( $j = $i+1; $j < count($array); $j++ )
if( $array[$j] < $tmp )
{
$k=$j;
$tmp = $array[$j];
}

// switch places of current element and previously found
$array[$k] = $array[$i];
$array[$i] = $tmp;
}

return $array;
}

No comments: