php实现选择排序法

选择排序法是一种简单的排序算法,其基本思想是每次从未排序的部分中选择最小(或最大)的元素,然后放到已排序部分的末尾。

以下是用PHP实现选择排序法的代码示例:

php 复制代码
<?php
function selectionSort($arr) {
    $n = count($arr);

    for ($i = 0; $i < $n - 1; $i++) {
        $minIndex = $i;

        for ($j = $i + 1; $j < $n; $j++) {
            if ($arr[$j] < $arr[$minIndex]) {
                $minIndex = $j;
            }
        }

        // Swap the minimum element with the first element of the unsorted sublist
        $temp = $arr[$i];
        $arr[$i] = $arr[$minIndex];
        $arr[$minIndex] = $temp;
    }

    return $arr;
}
// 示例用法
$arr = [64, 25, 12, 22, 11];
$sortedArr = selectionSort($arr);
print_r($sortedArr);

以上代码中,selectionSort函数接受一个数组作为参数,并返回按照升序排序后的数组。内部使用两层循环,$i表示已排序部分的末尾位置,$j用于遍历未排序部分,找到未排序部分中的最小元素索引$minIndex,然后将其与已排序部分的末尾元素交换位置。不断重复这个过程,直到遍历完所有元素,即可得到最终的排序结果。

相关推荐
山野0201 分钟前
index.php 和 php
开发语言·php
lifallen3 分钟前
笛卡尔树 (Cartesian Tree)
java·数据结构·算法
ab1515175 分钟前
2.15完成105、106、110
数据结构·算法
dalong1012 分钟前
A27:图像九宫格分割程序
笔记·aardio
麦德泽特14 分钟前
蓝牙与WiFi之外:为机器人选择合适的近距离无线通信技术
c语言·开发语言·安全·机器人·ssh
Web打印17 分钟前
Phpask(php集成环境)之02配置php
开发语言·php
不想看见40417 分钟前
N-Queens -- 回溯法 -- 力扣101算法题解笔记
java·数据结构·算法
赵谨言20 分钟前
基于Python和ArcPy的不动产数据入库技术与运用
大数据·开发语言·经验分享·python
MX_935921 分钟前
Spring组件扫描原理解析
java·后端·spring
—Miss. Z—22 分钟前
计算机软件资格考试—Python补充
开发语言·python