PHP Program to Implement Selection Sort

PHP Program to Implement Selection Sort

Sorting is a core concept in programming, and Selection Sort is one of the simplest algorithms to understand and implement. Unlike Bubble Sort, which repeatedly swaps adjacent elements, Selection Sort works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the array and placing it at the correct position. This makes it easy to see the progress of the sorting step by step, which is perfect for beginners learning how algorithms manipulate data.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Selection Sort may not be the most efficient algorithm for large datasets, but it has clear advantages in simplicity and stability for educational purposes. Learning Selection Sort in PHP helps beginners understand array indexing, loops, and conditional logic. It also provides a solid foundation for exploring more advanced sorting algorithms like Quick Sort and Merge Sort in the future. In this article, we will explore multiple ways to implement Selection Sort in PHP, helping you grasp the algorithm thoroughly.

Program 1: Basic Selection Sort Using Loops

This first program demonstrates a straightforward implementation of Selection Sort using nested loops. The algorithm repeatedly finds the minimum element in the unsorted portion of the array and swaps it with the first element of that portion.

<?php

function selectionSortBasic($array) {

    $n = count($array);

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

        $minIndex = $i;

        for ($j = $i + 1; $j < $n; $j++) {

            if ($array[$j] < $array[$minIndex]) {
                $minIndex = $j;
            }

        }

        if ($minIndex != $i) {

            $temp = $array[$i];
            $array[$i] = $array[$minIndex];
            $array[$minIndex] = $temp;

        }

    }

    return $array;

}

$data = [29, 10, 14, 37, 13];

$sorted = selectionSortBasic($data);

print_r($sorted);

?>

In this version, beginners can see how the minimum element “selects” its position in each pass. The inner loop identifies the smallest value, and the outer loop places it in the correct position, gradually creating a sorted portion at the start of the array.

Program 2: Selection Sort With Descending Order

Sometimes, you may want to sort data in descending order. This version modifies the comparison logic to find the maximum element instead of the minimum.

<?php

function selectionSortDescending($array) {

    $n = count($array);

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

        $maxIndex = $i;

        for ($j = $i + 1; $j < $n; $j++) {

            if ($array[$j] > $array[$maxIndex]) {
                $maxIndex = $j;
            }

        }

        if ($maxIndex != $i) {

            $temp = $array[$i];
            $array[$i] = $array[$maxIndex];
            $array[$maxIndex] = $temp;

        }

    }

    return $array;

}

$data = [7, 2, 9, 4, 1];

$sorted = selectionSortDescending($data);

print_r($sorted);

?>

This program teaches beginners how changing a single comparison can reverse the sort order. It also reinforces the concept of using loops to iterate and conditionally swap elements.

Program 3: Recursive Selection Sort

Selection Sort can also be implemented recursively. Each call selects the minimum element and places it at the start of the unsorted portion, then recursively sorts the remaining array.

<?php

function selectionSortRecursive($array, $start = 0) {

    $n = count($array);

    if ($start >= $n - 1) {
        return $array;
    }

    $minIndex = $start;

    for ($i = $start + 1; $i < $n; $i++) {

        if ($array[$i] < $array[$minIndex]) {
            $minIndex = $i;
        }

    }

    if ($minIndex != $start) {

        $temp = $array[$start];
        $array[$start] = $array[$minIndex];
        $array[$minIndex] = $temp;

    }

    return selectionSortRecursive($array, $start + 1);

}

$data = [20, 12, 8, 5, 15];

$sorted = selectionSortRecursive($data);

print_r($sorted);

?>

This recursive version helps beginners understand how algorithms can break down tasks into smaller steps. Each function call handles part of the array, gradually reducing the unsorted portion until the array is fully sorted.

Program 4: Selection Sort for Strings

Selection Sort isn’t limited to numbers. You can use it to sort strings alphabetically as well.

<?php

function selectionSortStrings($array) {

    $n = count($array);

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

        $minIndex = $i;

        for ($j = $i + 1; $j < $n; $j++) {

            if (strcmp($array[$j], $array[$minIndex]) < 0) {
                $minIndex = $j;
            }

        }

        if ($minIndex != $i) {

            $temp = $array[$i];
            $array[$i] = $array[$minIndex];
            $array[$minIndex] = $temp;

        }

    }

    return $array;

}

$data = ["Banana", "Apple", "Cherry", "Date"];

$sorted = selectionSortStrings($data);

print_r($sorted);

?>

Here, strcmp is used to compare strings alphabetically. Beginners learn that Selection Sort can be adapted to different data types simply by changing the comparison method.

Program 5: Selection Sort With Callback for Custom Logic

For maximum flexibility, you can pass a callback function to define custom sorting logic. This allows sorting of numbers, strings, or arrays of objects.

<?php

function selectionSortCallback($array, $compare) {

    $n = count($array);

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

        $extremeIndex = $i;

        for ($j = $i + 1; $j < $n; $j++) {

            if ($compare($array[$j], $array[$extremeIndex]) < 0) {
                $extremeIndex = $j;
            }

        }

        if ($extremeIndex != $i) {

            $temp = $array[$i];
            $array[$i] = $array[$extremeIndex];
            $array[$extremeIndex] = $temp;

        }

    }

    return $array;

}

$data = [
    ["name" => "Alice", "age" => 25],
    ["name" => "Bob", "age" => 22],
    ["name" => "Charlie", "age" => 28]
];

$sorted = selectionSortCallback($data, function($a, $b) {
    return $a["age"] - $b["age"];
});

print_r($sorted);

?>

This version demonstrates how Selection Sort can be made highly reusable. By defining the comparison externally, you can sort by any property or custom rule, which is excellent for real-world PHP applications.

Frequently Asked Questions (FAQ)

This section answers common questions beginners ask about Selection Sort in PHP.

Q1. How is Selection Sort different from Bubble Sort?
Selection Sort selects the minimum element and moves it to the correct position, while Bubble Sort repeatedly swaps adjacent elements. Selection Sort usually performs fewer swaps than Bubble Sort.

Q2. Is Selection Sort efficient for large arrays?
Selection Sort has a time complexity of O(n²), so it is not recommended for large datasets. It is ideal for learning and small arrays.

Q3. Can Selection Sort sort strings?
Yes. By using strcmp or a similar function, Selection Sort can order strings alphabetically.

Q4. Can Selection Sort be implemented recursively?
Yes. Recursive implementations break the problem into smaller parts, which is useful for learning recursion and understanding algorithm flow.

Q5. Is Selection Sort a stable algorithm?
By default, Selection Sort is not stable, because swapping may change the relative order of equal elements. Stability can be maintained with careful implementation.

Conclusion

Selection Sort is a simple yet powerful algorithm for beginners to learn about sorting in PHP. By exploring multiple implementations—from basic loops to recursion, string sorting, and callback-based custom sorting—learners gain a strong understanding of array manipulation, conditional logic, and algorithm design. Practicing these programs helps beginners build confidence and lays the foundation for mastering more advanced sorting techniques. Selection Sort teaches the importance of systematic thinking and careful comparisons in programming, which are essential skills for every developer.

Scroll to Top