Implement Selection Sort in PHP

The outer loop need to continue iterate from the index 0 to n – 1( here n is the number of items). The inner loop starts from the current index + 1 of the outer loop to the end of the list.

function selection_sort( $data_array ){
	for( $i=0; $i < count( $data_array ) - 1; $i++ ){
		$temp = $data_array[$i];
		$min_index = $i;
		for( $j=$i+1; $j < count( $data_array ); $j++ ){
			if( $data_array[$j] < $data_array[$min_index] ){
				$min_index = $j;
			}
		}
		if( $i != $min_index ){
			$data_array[$i] = $data_array[$min_index];
			$data_array[$min_index] = $temp;
		}
	}
	return $data_array;
}

echo '<h1>Before Sort</h1>';
echo '<pre>';
print_r($data_array);
echo '</pre>';
echo "<br>";
echo '<h1>After Sort</h1>';
$sorted_items = selection_sort( $data_array ); 
echo '<pre>';
print_r($sorted_items);
echo '</pre>';

Output:

Leave a Reply

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