Sorting is a common task in programming, and one of the simplest algorithms that beginners enjoy learning is Insertion Sort. It works in a very natural way, almost like how people arrange playing cards in their hands. Each card is taken one at a time and placed into the correct position among the cards already sorted. Insertion Sort follows this same idea, making it easy to understand and visualize.
with hands-on learning.
get the skills and confidence to land your next move.
This algorithm is especially useful when working with small datasets or when the data is already partially sorted. It performs well in these situations and offers a clear learning path for building a deeper understanding of sorting logic in PHP. Because it touches on loops, comparisons, and array manipulation, Insertion Sort becomes a great stepping stone before moving on to more advanced algorithms like Merge Sort or Quick Sort. In this article, we look at several PHP programs that show different ways to implement Insertion Sort, helping you strengthen both your logic and coding skills.
Program 1: Basic Insertion Sort Using Loops
This program shows the classic form of Insertion Sort using simple loops. It starts from the second element and gradually builds the sorted portion by inserting each element into the correct place within the growing sorted section.
<?php
function insertionSortBasic($array) {
$n = count($array);
for ($i = 1; $i < $n; $i++) {
$key = $array[$i];
$j = $i - 1;
while ($j >= 0 && $array[$j] > $key) {
$array[$j + 1] = $array[$j];
$j--;
}
$array[$j + 1] = $key;
}
return $array;
}
$data = [34, 8, 64, 51, 32, 21];
$sorted = insertionSortBasic($data);
print_r($sorted);
?>This version is great for understanding the flow of the algorithm. Each loop takes one value, compares it with earlier values, shifts larger values forward, and finally inserts the key in the correct spot. Beginners can easily follow the logic because the steps mirror real-life sorting by hand.
Program 2: Insertion Sort in Descending Order
Sometimes you may want the list sorted from highest to lowest. This version uses the same logic but reverses the comparison so that each new value is positioned based on descending order instead of ascending.
<?php
function insertionSortDescending($array) {
$n = count($array);
for ($i = 1; $i < $n; $i++) {
$key = $array[$i];
$j = $i - 1;
while ($j >= 0 && $array[$j] < $key) {
$array[$j + 1] = $array[$j];
$j--;
}
$array[$j + 1] = $key;
}
return $array;
}
$data = [15, 3, 27, 12, 9];
$sorted = insertionSortDescending($data);
print_r($sorted);
?>This shows how small logic changes can adjust the entire behavior of a sorting algorithm. By switching the comparison direction, the algorithm selects higher numbers first instead of smaller ones. It helps beginners understand how flexible sorting logic can be.
Program 3: Recursive Insertion Sort
Insertion Sort can also be implemented using recursion. This form sorts the array up to one index, then inserts the next element into the correct position by breaking the task into smaller steps.
<?php
function recursiveInsertionSort(&$array, $n = null) {
if ($n === null) {
$n = count($array);
}
if ($n <= 1) {
return;
}
recursiveInsertionSort($array, $n - 1);
$last = $array[$n - 1];
$j = $n - 2;
while ($j >= 0 && $array[$j] > $last) {
$array[$j + 1] = $array[$j];
$j--;
}
$array[$j + 1] = $last;
}
$data = [5, 2, 9, 1, 5, 6];
recursiveInsertionSort($data);
print_r($data);
?>This recursive version helps learners think in terms of smaller subproblems. Each recursion handles a part of the array, slowly building the sorted section. It is a helpful introduction to the idea that algorithms can solve problems by reducing them into simpler versions of the same problem.
Program 4: Insertion Sort for Strings
Insertion Sort is not limited to numbers. It can also be used to sort strings alphabetically. This version sorts an array of words in ascending order.
<?php
function insertionSortStrings($array) {
$n = count($array);
for ($i = 1; $i < $n; $i++) {
$key = $array[$i];
$j = $i - 1;
while ($j >= 0 && strcmp($array[$j], $key) > 0) {
$array[$j + 1] = $array[$j];
$j--;
}
$array[$j + 1] = $key;
}
return $array;
}
$data = ["Orange", "Apple", "Banana", "Grape"];
$sorted = insertionSortStrings($data);
print_r($sorted);
?>By using strcmp, the algorithm compares strings based on alphabetical order. This demonstrates that sorting does not depend only on numbers; it can work on any data type as long as you define how to compare values.
Program 5: Insertion Sort With Custom Comparison Logic
For more control, you can define a custom comparison function. This allows sorting by any rule you choose, such as sorting objects or associative arrays by a specific property.
<?php
function insertionSortCustom($array, $compare) {
$n = count($array);
for ($i = 1; $i < $n; $i++) {
$key = $array[$i];
$j = $i - 1;
while ($j >= 0 && $compare($array[$j], $key) > 0) {
$array[$j + 1] = $array[$j];
$j--;
}
$array[$j + 1] = $key;
}
return $array;
}
$data = [
["name" => "Alice", "score" => 82],
["name" => "Bob", "score" => 75],
["name" => "Charlie", "score" => 90],
];
$sorted = insertionSortCustom($data, function($a, $b) {
return $a["score"] - $b["score"];
});
print_r($sorted);
?>This version opens the door to advanced sorting scenarios. By passing a callback, you decide how the data should be ordered. This is especially useful when working with structured data or building dynamic sorting systems in PHP applications.
Frequently Asked Questions (FAQ)
This section offers short answers to common questions about Insertion Sort in PHP.
Q1. What makes Insertion Sort easy for beginners?
Its step-by-step logic mirrors how people sort things manually, making it simple to visualize and understand.
Q2. Is Insertion Sort efficient for large datasets?
Insertion Sort has a time complexity of O(n²), so it is best suited for small or partially sorted datasets.
Q3. Can Insertion Sort handle strings?
Yes. By using string comparison functions like strcmp, it can sort text data alphabetically.
Q4. What is the advantage of using recursion in Insertion Sort?
Recursion helps break the problem into smaller parts, making the algorithm’s flow clearer for learners.
Q5. When should a custom comparison function be used?
It should be used when sorting complex data structures such as objects or associative arrays.
Conclusion
Insertion Sort is one of the most beginner-friendly sorting algorithms in PHP. It teaches important lessons about comparisons, loops, shifting elements, and algorithm design. By exploring different versions—basic loops, descending order, recursion, string sorting, and custom comparison—you gain a full understanding of how flexible and useful this algorithm can be. Even though it is not the fastest for large datasets, it remains an excellent educational tool and a practical solution for smaller tasks. Keep experimenting with it, try your own variations, and you will continue improving your programming confidence and skill.




