How to write a custom PHP array sorting algorithm? Bubble sort: Sorts an array by comparing and exchanging adjacent elements. Selection sort: Select the smallest or largest element each time and swap it with the current position. Insertion sort: Insert elements one by one into the sorted part.
Guidelines for writing PHP array custom sorting algorithm
Introduction
Array sorting is programming A common task that allows us to reorganize elements in an array based on specific criteria. PHP provides a variety of built-in sorting algorithms, but sometimes we need to sort arrays based on custom logic, which requires us to write our own custom sorting algorithm.
Bubble sort
Bubble sort is a simple sorting algorithm that sorts an array by repeatedly comparing adjacent elements and exchanging their positions.
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
Selection sort is a sorting algorithm based on selecting the smallest or largest element and exchanging it with its current position.
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
Insertion sort is a sorting algorithm based on inserting elements one by one into an ordered part.
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; } }
Practical case
Let us use the bubble sort algorithm to sort the following PHP array in ascending order:
$arr = [5, 2, 8, 3, 1];
Call the bubble sort function:
bubbleSort($arr);
Sorted array:
[1, 2, 3, 5, 8]
The above is the detailed content of Guide to writing a custom sorting algorithm for PHP arrays. For more information, please follow other related articles on the PHP Chinese website!