blogs

Selection Sort

Posted 31 October 2017

Selection sort i s another comparison based sorting algorithm. It similar to bubble sort but it will take fewer swapping than Bubble short  In Selection sort first we find minimum/ maximum value item of the array and place in to first place . If  sorting is ascending order we will take minimum value from the array  if sorting descending order we will take maximum value from the array.  In the second iteration we find second most minimum / maximum value from the array and place in to second place. This goes until we placed each numbers correctly sorted position.

 

As we Preceding image  We started with first item in the list which is 20. when we iterate the 1st loop.  we found the minimum value is 10  so we swapped place of 20  and vice versa. we have added minimum value. now we want to find second smallest value  from the array compared to second item which is 45 in right side now we able to see 20 is the smallest value than 45 now we swapped in to  2nd place , so it continue until the last elements

Now we implement the Selection Sort

function selectionSort($array)
{
    $len = count($array);

    for ($i = 0; $i < $len; $i++) {
        $min = $i;

        for ($j = $i + 1; $j < $len; $j++) {
            if ($array[$j] < $array[$min]) {
                $min = $j;
            }
        }


        if ($i != $min) {
            $tmp = $array[$i];
            $array[$i] = $array[$min];
            $array[$min] = $tmp;
        }
    }

    return $array;
}

You can see above it sorted ascending order if you want to descending order. simply you can change $array[$j] < $array[$min] to $array[$j] > $array[$min] and change $min to $max

Selection sort has two for loop with O to n but Selection Sort makes maximum n-1 number of swapping Selection sort best case , worst case and average case have similar complexity  O(n2)

 

Leave a Reply

Your email address will not be published. Required fields are marked *