PHP Program to Implement Shell Sort

PHP Program to Implement Shell Sort

Sorting is one of the most important concepts in programming. Whether you are organizing a list of names, arranging numbers, or preparing data for faster searching, sorting makes your code efficient and easier to manage. Among the various sorting algorithms, Shell Sort stands out as a simple yet powerful method that improves on the basic insertion sort by allowing the exchange of items that are far apart. This means it can handle moderately large datasets more efficiently than some simpler algorithms.

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

Shell Sort is particularly useful when you want a straightforward sorting method without getting into highly complex algorithms like Quick Sort or Merge Sort. It’s a practical choice for beginners because it helps you understand how incremental comparisons and swaps can drastically improve performance. You will often see Shell Sort used in applications where data is mostly sorted but occasionally contains unsorted elements, such as organizing user scores, arranging logs, or maintaining ordered lists in websites or simple databases.

Program 1: Basic Shell Sort Using Loops

This program demonstrates the traditional way of implementing Shell Sort using loops. It sorts an array of predefined numbers in ascending order.

<?php

$array = [23, 12, 1, 8, 34, 54, 2, 3];
$n = count($array);

$gap = floor($n / 2);

while ($gap > 0) {

    for ($i = $gap; $i < $n; $i++) {

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

        while ($j >= $gap && $array[$j - $gap] > $temp) {
            $array[$j] = $array[$j - $gap];
            $j -= $gap;
        }

        $array[$j] = $temp;

    }

    $gap = floor($gap / 2);

}

echo "Sorted Array: ";

print_r($array);

?>

This code starts by setting a gap that divides the array into sublists. Elements that are far apart are compared and swapped if necessary. The gap gradually reduces until the array becomes fully sorted. Beginners can easily follow this program because it shows how loops and conditions interact to sort a dataset step by step. It’s useful for understanding the underlying logic behind efficient sorting without overwhelming complexity.

Program 2: Shell Sort Using a Function

Here, we define a reusable function for Shell Sort. This approach makes your code cleaner and easier to use with multiple arrays.

<?php

function shellSort($arr) {

    $n = count($arr);
    $gap = floor($n / 2);

    while ($gap > 0) {

        for ($i = $gap; $i < $n; $i++) {

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

            while ($j >= $gap && $arr[$j - $gap] > $temp) {
                $arr[$j] = $arr[$j - $gap];
                $j -= $gap;
            }

            $arr[$j] = $temp;

        }

        $gap = floor($gap / 2);

    }

    return $arr;

}

$array = [9, 7, 5, 3, 1];
$sortedArray = shellSort($array);

echo "Sorted Array: ";
print_r($sortedArray);

?>

By wrapping Shell Sort in a function, you can sort any array by simply calling shellSort(). This makes your code modular and beginner-friendly. It’s also easier to understand the flow because the function encapsulates the sorting logic, allowing learners to focus on input and output separately.

Program 3: Shell Sort With Descending Order

This program shows how Shell Sort can be modified to sort elements in descending order instead of ascending.

<?php

$array = [4, 10, 2, 8, 6];
$n = count($array);
$gap = floor($n / 2);

while ($gap > 0) {

    for ($i = $gap; $i < $n; $i++) {

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

        while ($j >= $gap && $array[$j - $gap] < $temp) {
            $array[$j] = $array[$j - $gap];
            $j -= $gap;
        }

        $array[$j] = $temp;

    }

    $gap = floor($gap / 2);

}

echo "Descending Sorted Array: ";
print_r($array);

?>

This program is nearly identical to the ascending version, but the comparison operator is reversed. This small change shows beginners how flexible Shell Sort can be. It is useful when you want to arrange items from highest to lowest, such as ranking scores or listing products by popularity.

Program 4: Recursive Shell Sort

Although Shell Sort is typically iterative, you can implement its core logic recursively by focusing on sorting subarrays defined by the gap. This example demonstrates the idea for educational purposes.

<?php

function shellSortRecursive(&$arr, $n, $gap) {

    if ($gap <= 0) return;

    for ($i = $gap; $i < $n; $i++) {

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

        while ($j >= $gap && $arr[$j - $gap] > $temp) {
            $arr[$j] = $arr[$j - $gap];
            $j -= $gap;
        }

        $arr[$j] = $temp;

    }

    shellSortRecursive($arr, $n, floor($gap / 2));

}

$array = [29, 10, 14, 37, 13];
$n = count($array);

shellSortRecursive($array, $n, floor($n / 2));

echo "Sorted Array using Recursion: ";
print_r($array);

?>

This recursive approach teaches beginners how functions can call themselves to repeat operations on smaller parts of the array. While not the most common method for Shell Sort, it’s a great exercise for understanding recursion and algorithmic thinking.

Program 5: Shell Sort With Strings

Shell Sort is not limited to numbers. You can also sort strings alphabetically. This program sorts an array of animal names.

<?php

$animals = ["Zebra", "Elephant", "Lion", "Monkey", "Cat"];
$n = count($animals);
$gap = floor($n / 2);

while ($gap > 0) {

    for ($i = $gap; $i < $n; $i++) {

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

        while ($j >= $gap && strcmp($animals[$j - $gap], $temp) > 0) {
            $animals[$j] = $animals[$j - $gap];
            $j -= $gap;
        }

        $animals[$j] = $temp;

    }

    $gap = floor($gap / 2);

}

echo "Alphabetically Sorted Animals: ";

print_r($animals);

?>

This example shows that Shell Sort works for text data, not just numbers. By using strcmp, we can compare strings accurately. Beginners will find this useful for real-world applications like sorting names, product titles, or any text-based data.

Frequently Asked Questions (FAQ)

Sorting data efficiently is essential, and beginners often have common questions about Shell Sort and PHP implementation.

Q1: What is the main advantage of Shell Sort over simple insertion sort?
Shell Sort can move elements farther in each step, reducing the number of comparisons and shifts required. It is faster than insertion sort for medium-sized arrays.

Q2: Can Shell Sort be used for large datasets?
Yes, it can handle moderately large datasets, but for very large datasets, algorithms like Merge Sort or Quick Sort may perform better.

Q3: Does Shell Sort work with strings in PHP?
Absolutely. By using strcmp or similar string comparison functions, Shell Sort can order strings alphabetically.

Q4: Is Shell Sort stable?
Shell Sort is not a stable sorting algorithm. Equal elements may not preserve their original order.

Q5: Why is the gap reduced gradually?
Reducing the gap step by step allows distant elements to move closer to their final position early on, improving overall efficiency.

Conclusion

Shell Sort is a simple yet powerful algorithm that gives beginners a clear understanding of sorting logic and array manipulation. Through loops, functions, recursion, and even string sorting, it shows how versatile a single algorithm can be. By practicing these programs in PHP, you’ll strengthen your grasp of arrays, loops, and conditionals while learning a useful tool for real-world data organization. Sorting doesn’t have to be intimidating, and Shell Sort is a perfect starting point to build confidence and explore more advanced algorithms in the future.

Scroll to Top