Open In App

PHP Program for Selection Sort

This article will show you how to sort the array elements using the Selection sort in PHP.

Selection Sort

Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and moving it to the sorted portion.



Selection Sort is a simple sorting algorithm that divides the input array into two parts: the sorted and the unsorted subarrays. The algorithm iterates through the unsorted subarray, finds the minimum element, and swaps it with the first element of the unsorted subarray. This process is repeated until the entire array is sorted.

 



Example: Here, sort the array elements using Selection sort.




<?php
  
function selectionSort($arr) {
    $n = count($arr);
    for($i = 0; $i < $n ; $i++) {
        $low = $i;
        for($j = $i + 1; $j < $n ; $j++) {
            if ($arr[$j] < $arr[$low]) {
                $low = $j;
            }
        }
          
        // Swap the minimum value to $ith node
        if ($arr[$i] > $arr[$low]) {
            $tmp = $arr[$i];
            $arr[$i] = $arr[$low];
            $arr[$low] = $tmp;
        }
    }
      
    return $arr;
}
  
// Driver Code
$arr = array(64, 25, 12, 22, 11);
  
$sortedArr = selectionSort($arr);
  
echo "Sorted Array: " . implode(" ", $sortedArr);
  
?> 

Output
Sorted Array: 11 12 22 25 64 

Article Tags :