PHP Program to Implement Quick Sort

PHP Program to Implement Quick Sort

Quick Sort is one of the most powerful and widely used sorting algorithms in computer science. It is known for its impressive speed and the way it breaks a large problem into smaller ones using a simple but clever idea. When you begin learning sorting algorithms, Quick Sort stands out because it teaches important ideas like partitioning, recursion, and efficient data handling. Even though its name sounds intense, the algorithm itself is quite friendly once you get the hang of it.

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

Quick Sort matters because of how efficiently it handles large datasets. Many modern systems and programming languages use variations of Quick Sort behind the scenes because of its great performance in real-world scenarios. It works by choosing a “pivot,” reorganizing the array around that pivot, and then repeating the process until everything is sorted. This divide-and-conquer style makes it faster than many simpler algorithms like Bubble Sort or Insertion Sort. In this article, we explore Quick Sort in PHP and present several full programs that approach the algorithm from different angles, giving beginners many ways to understand and practice it.

Program 1: Basic Quick Sort Using Recursion

This first version introduces the most popular form of Quick Sort. It uses recursion to repeat the sorting steps on smaller sections of the array. It starts by choosing a pivot, creating two sides around the pivot, and then sorting those sides.

<?php

function quickSortBasic($array) {

    if (count($array) < 2) {
        return $array;
    }

    $pivot = $array[0];
    $left = [];
    $right = [];

    for ($i = 1; $i < count($array); $i++) {

        if ($array[$i] <= $pivot) {
            $left[] = $array[$i];
        } else {
            $right[] = $array[$i];
        }

    }

    return array_merge(quickSortBasic($left), [$pivot], quickSortBasic($right));

}

$data = [34, 7, 23, 32, 5, 62];
$sorted = quickSortBasic($data);

print_r($sorted);

?>

This simple version helps beginners see how Quick Sort divides the problem step by step. The pivot separates the data, and the recursive calls continue sorting until every chunk becomes small enough to return immediately. It is easy to trace through the steps, making it great for anyone seeing the algorithm for the first time.

Program 2: Quick Sort Using the Last Element as Pivot

Another common variation is to use the last element as the pivot. This version works the same way but changes how the pivot is chosen. Doing this helps learners understand that the pivot can be selected in many ways.

<?php

function quickSortLastPivot($array) {

    if (count($array) < 2) {
        return $array;
    }

    $pivot = $array[count($array) - 1];
    $left = [];
    $right = [];

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

        if ($array[$i] < $pivot) {
            $left[] = $array[$i];
        } else {
            $right[] = $array[$i];
        }

    }

    return array_merge(quickSortLastPivot($left), [$pivot], quickSortLastPivot($right));

}

$data = [10, 80, 30, 90, 40, 50, 70];
$sorted = quickSortLastPivot($data);

print_r($sorted);

?>

This version shows how small changes in pivot selection can influence the algorithm. It teaches flexibility while still keeping the main Quick Sort idea intact. Many real implementations choose different pivot strategies depending on performance needs, so this is a useful step forward.

Program 3: In-Place Quick Sort With Index-Based Partitioning

This program introduces a slightly more advanced but very practical version. Instead of creating new arrays for left and right sides, it sorts the array in place using indexes. This is how Quick Sort is often used in professional codebases.

<?php

function quickSortInPlace(&$array, $low, $high) {

    if ($low < $high) {

        $pivotIndex = partition($array, $low, $high);

        quickSortInPlace($array, $low, $pivotIndex - 1);
        quickSortInPlace($array, $pivotIndex + 1, $high);

    }

}

function partition(&$array, $low, $high) {

    $pivot = $array[$high];
    $i = $low - 1;

    for ($j = $low; $j < $high; $j++) {

        if ($array[$j] <= $pivot) {

            $i++;

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

        }

    }

    $temp = $array[$i + 1];
    $array[$i + 1] = $array[$high];
    $array[$high] = $temp;

    return $i + 1;

}

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

quickSortInPlace($data, 0, count($data) - 1);

print_r($data);

?>

This style is closer to what high-performance applications use. Sorting in place saves memory and speeds up the process. While it looks more technical, it still follows the same core idea of partitioning around a pivot. Beginners can understand it by stepping through each swap and watching how the pivot moves into the correct spot.

Program 4: Quick Sort for Strings

Just like other sorting algorithms, Quick Sort is not limited to numbers. This program shows how to sort an array of strings alphabetically using the same logic.

<?php

function quickSortStrings($array) {

    if (count($array) < 2) {
        return $array;
    }

    $pivot = $array[0];
    $left = [];
    $right = [];

    for ($i = 1; $i < count($array); $i++) {

        if (strcmp($array[$i], $pivot) <= 0) {
            $left[] = $array[$i];
        } else {
            $right[] = $array[$i];
        }

    }

    return array_merge(quickSortStrings($left), [$pivot], quickSortStrings($right));

}

$data = ["Orange", "Apple", "Banana", "Grape"];

$sorted = quickSortStrings($data);

print_r($sorted);

?>

This highlights Quick Sort’s ability to work with many data types. By using string comparison, PHP handles the alphabetical ordering while the algorithm manages the structure. It is a clean way to learn how sorting applies beyond numbers.

Program 5: Quick Sort With Custom Comparator

Sometimes you want full control over how the data is sorted. This version lets you pass your own comparison logic so that you can sort objects, associative arrays, or any structure.

<?php

function quickSortCustom($array, $compare) {

    if (count($array) < 2) {
        return $array;
    }

    $pivot = $array[0];
    $left = [];
    $right = [];

    for ($i = 1; $i < count($array); $i++) {

        if ($compare($array[$i], $pivot) <= 0) {
            $left[] = $array[$i];
        } else {
            $right[] = $array[$i];
        }

    }

    return array_merge(
        quickSortCustom($left, $compare),
        [$pivot],
        quickSortCustom($right, $compare)
    );

}

$data = [
    ["name" => "Alice", "age" => 25],
    ["name" => "Bob", "age" => 19],
    ["name" => "Charlie", "age" => 30]
];

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

print_r($sorted);

?>

This approach opens the door to many custom sorting possibilities. Whether you want to sort by age, score, date, or any field, the comparator gives you total freedom. It extends the usefulness of Quick Sort far beyond simple arrays.

Frequently Asked Questions (FAQ)

This section answers common questions that beginners often ask when learning Quick Sort in PHP.

Q1. Why is Quick Sort faster than simple sorting algorithms?
It uses a divide-and-conquer technique that reduces the sorting work dramatically, especially for large datasets.

Q2. Does Quick Sort always choose the first element as the pivot?
No. The pivot can be chosen in many ways, such as the first element, last element, middle element, or even a random one.

Q3. Can Quick Sort handle strings and complex data?
Yes. As long as you provide a comparison rule, Quick Sort can sort strings, objects, and associative arrays.

Q4. Is Quick Sort stable?
Traditional Quick Sort is not stable, but it can be made stable with additional steps if needed.

Q5. Why is recursion used in Quick Sort?
Recursion helps break the large problem into smaller sorting jobs until each part becomes simple to handle.

Conclusion

Quick Sort is a powerful and elegant algorithm that every PHP learner should know. It shows how dividing a problem into smaller pieces can lead to fast and efficient solutions. By exploring different versions—basic recursion, pivot variations, in-place sorting, string sorting, and custom comparison—you gain a wide understanding of what makes Quick Sort so flexible and useful. With practice, you will not only master this algorithm but also improve your overall problem-solving skills in PHP. Keep experimenting, try new datasets, and enjoy the journey of becoming more confident with algorithms.

Scroll to Top