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

相关推荐
码事漫谈6 小时前
当AI开始“思考”:我们是否真的准备好了?
前端·后端
2301_764441336 小时前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
014-code6 小时前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
lly2024067 小时前
组合模式(Composite Pattern)
开发语言
玉树临风ives7 小时前
atcoder ABC 452 题解
数据结构·算法
游乐码7 小时前
c#泛型约束
开发语言·c#
大连好光景7 小时前
PYG从入门到放弃
笔记·学习
Dontla7 小时前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen7 小时前
python rest请求、requests
开发语言·python
铁东博客7 小时前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang