Guide to writing a custom sorting algorithm for PHP arrays

WBOY
Release: 2024-04-27 18:12:01
Original
512 people have browsed it

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.

PHP 数组自定义排序算法的编写指南

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; } } } }
Copy after login

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; } }
Copy after login

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; } }
Copy after login

Practical case
Let us use the bubble sort algorithm to sort the following PHP array in ascending order:

$arr = [5, 2, 8, 3, 1];
Copy after login

Call the bubble sort function:

bubbleSort($arr);
Copy after login

Sorted array:

[1, 2, 3, 5, 8]
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!