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

相关推荐
GetcharZp6 小时前
GitHub 49K+ Star!C++ 开发者必知的 JSON 神级库:从零到精通全指北
后端
fqbqrr6 小时前
2606C++,C++构的多态
开发语言·c++
问心无愧05136 小时前
ctf show web入门111
android·前端·笔记
xujinwei_gingko6 小时前
SpringBoot整合WebSocket
spring boot·后端·websocket
智码看视界6 小时前
现代Web开发基础:全栈工程师的起航点
前端·后端·c5全栈
程序员cxuan6 小时前
Claude Fable 5 来了
人工智能·后端·程序员
biter down7 小时前
从 0 到 1 搭建 Python 接口自动化测试框架(博客系统实战)
开发语言·python
JS菌7 小时前
手写一个 AI Agent 全栈项目:从沙箱执行到子智能体的完整实现
前端·人工智能·后端
wang09077 小时前
自己动手写一个spring之IOC_2
java·后端·spring