PHP: selection sort implementation

Selection sort has an outer loop and an inner loop. The outer loop starts from the first element to the second element to the end, because when it gets to the element right before the last element, the last element should be in its correct position. The inner loop starts from the current index+1 of the outer loop to the end of the list. When the inner loop finishes, it will swap the current index of the outer loop with the next minimum(for ascending) or maximum(for descending) value.

Here is an example of selection sort in php

<?php

function selectionSort($data)
{
	$n=count($data);
	$nextSwap=null;		//the index of next min value or max value
	$temp=null;

	for($i=0; $i<$n-1; $i++)//outer loop
	{

		$nextSwap=$i;
		for($j=$i+1; $j<$n; $j++)//inner loop
		{
			if( $data[$j]<$data[$nextSwap] ) //change the < to > for descending order
			{
				$nextSwap=$j; 
			}
		}

		//swap the current index of the outer loop with the next min value
		$temp=$data[$i];
		$data[$i]=$data[$nextSwap];
		$data[$nextSwap]=$temp;
	}

	return $data;
}

echo implode(",",array(43,23,4,11,2,88,76,46));
echo "<br>";
echo implode(",",selectionSort(array(43,23,4,11,2,88,76,46)));

demo

Search within Codexpedia

Custom Search

Search the entire web

Custom Search