Array sorting is a common task in programming that helps us rearrange the elements of an array according to specified rules. PHP provides several built-in sorting functions, but in certain scenarios, we may need to write our own sorting algorithms to meet specific needs. In this article, we will focus on how to write custom PHP array sorting algorithms, including the bubble sort, selection sort, and insertion sort algorithms, with practical code examples.
Bubble sort is a simple sorting algorithm that repeatedly compares adjacent elements and swaps them until the entire array is sorted. Its time complexity is O(n²), so it is more suitable for small data sets.
function bubbleSort(array &$arr) {
$n = count($arr);
for ($i = 0; $i < $n - 1; $i++) {
for ($j = 0; $j < $n - $i - 1; $j++) {
if ($arr[$j] > $arr[$j + 1]) {
$tmp = $arr[$j];
$arr[$j] = $arr[$j + 1];
$arr[$j + 1] = $tmp;
}
}
}
}
Selection sort works by selecting the smallest (or largest) element from the unsorted part and placing it at the end of the sorted part. While it offers some optimization over bubble sort, its time complexity is still O(n²), making it suitable for small-scale sorting tasks.
function selectionSort(array &$arr) {
$n = count($arr);
for ($i = 0; $i < $n - 1; $i++) {
$min_idx = $i;
for ($j = $i + 1; $j < $n; $j++) {
if ($arr[$j] < $arr[$min_idx]) {
$min_idx = $j;
}
}
$tmp = $arr[$i];
$arr[$i] = $arr[$min_idx];
$arr[$min_idx] = $tmp;
}
}
Insertion sort is an algorithm that builds the sorted array one element at a time by inserting each new element into the sorted part. Its time complexity is O(n²), but it is efficient when dealing with small datasets. It is commonly used for sorting small arrays.
function insertionSort(array &$arr) {
$n = count($arr);
for ($i = 1; $i < $n; $i++) {
$key = $arr[$i];
$j = $i - 1;
while ($j >= 0 && $arr[$j] > $key) {
$arr[$j + 1] = $arr[$j];
$j--;
}
$arr[$j + 1] = $key;
}
}
Now, let's use the bubble sort algorithm to sort a PHP array in ascending order:
$arr = [5, 2, 8, 3, 1];
bubbleSort($arr);
The sorted array will be:
[1, 2, 3, 5, 8]
This article covered three common PHP array sorting algorithms: bubble sort, selection sort, and insertion sort. While these algorithms are simple, they provide a good foundation for understanding sorting algorithms. In practical development, you can choose the appropriate sorting method based on your specific requirements. For more efficient sorting, you can also consider using PHP's built-in sorting functions, such as sort() and usort().