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

相关推荐
IT_陈寒2 分钟前
Vue的v-for里用index当key,我被自己坑惨了
前端·人工智能·后端
invicinble27 分钟前
Spring如何把bean注册到容器里
java·后端·spring
gumichef30 分钟前
算法的时间复杂度和空间复杂度
数据结构
S1998_1997111609•X41 分钟前
MacOS/ˉsh(so.))os.apkair/AI
开发语言·网络·人工智能
SimpleLearingAI42 分钟前
C++虚函数详解
开发语言·c++
阿丰资源1 小时前
基于SpringBoot+MySQL的网上订餐系统(附源码)
spring boot·后端·mysql
希望永不加班1 小时前
SpringBoot 敏感数据脱敏(序列化层)
java·spring boot·后端·spring
Dxy12393102161 小时前
Python使用XPath定位元素:动态计算与函数调用
开发语言·python
希望永不加班1 小时前
SpringBoot 数据库索引优化:慢查询分析
java·数据库·spring boot·后端·spring
cpp_25011 小时前
P1832 A+B Problem(再升级)
数据结构·c++·算法·动态规划·题解·洛谷·背包dp