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,然后将其与已排序部分的末尾元素交换位置。不断重复这个过程,直到遍历完所有元素,即可得到最终的排序结果。

相关推荐
Dilee几秒前
Spring AI 对话记忆:MessageChatMemoryAdvisor 最小接入
后端
星环科技1 分钟前
数据标准Agent ,让企业数据说同一种语言
java·开发语言·前端
自小吃多1 分钟前
IVD设备-以GB4793.1做安规摸底
笔记·嵌入式硬件
游码峰行3 分钟前
游戏脚本挂攻防-在PoW中实现动态Hash策略及应用实践
后端
一条泥憨鱼4 分钟前
苍穹外卖【day6|微信登录与商品浏览功能】
后端·mybatis·苍穹外卖
凌波粒5 分钟前
LeetCode--90.子集II(回溯算法)
数据结构·算法·leetcode
用户762352425916 分钟前
Kafka客户端消息流转流程
后端
橘子星6 分钟前
深入理解 AJAX 中的 JSON 序列化与 JS 异步处理
前端·javascript·后端
SimonKing6 分钟前
Qoder 提供免费 Qwen3.7-Max,无需订阅
java·后端·程序员
凌波粒14 分钟前
LeetCode--46.全排列(回溯算法)
数据结构·算法·leetcode