The Selection Sort Algorithm mainly works as compares two successive elements of an array repeatedly and swapping if necessary.
Working of Selection Sort
It is based of minimum and maximum value. First check maximum or largest value in array list and place it into first position like (Set FIRST) of array, next find the minimum or smallest element in array list Like (Set SECOND) and then Swap SECOND with FIRST.
Algorithm
function select(list[1..n], k)
for i from 1 to k
minIndex = i
minValue = list[i]
for j from i+1 to n
if list[j] < minValue
minIndex = j
minValue = list[j]
swap list[i] and list[minIndex]
return list[k]
Program
//Display Sort
function display($array){
$size = count($array);
$message = "";
for($i=0;$i<$size;$i++){
$message .= $array[$i];
$message .= ($size==$i+1)? ".": ",";
}
return $message;
}
//Selection Sort
function selection_sort($array){
$size = count($array);
for($i=0;$i<$size;$i++){
for($j=$i+1;$j<$size;$j++){
if($array[$i]>$array[$j]){
$temp = $array[$i];
$temp_b = $array[$j];
$array[$i] = $temp_b;
}
}
}
return $array;
}
$array = [34,304, 302,745,91,5,764,200];
echo "<p>".display($array)."</p>";
$sort_array = selection_sort($array);
echo "<p>".display($sort_array)."</p>";
(Visited 191 times, 1 visits today)
