PHP排序算法:数组内有A~E,A移到C或者C移到B后排序,还按原顺序排序,循环

效果


PHP代码

php 复制代码
 public function demo($params)
    {
        function moveNext($arr)
        {
            $length = count($arr);
            $lastElement = $arr[$length - 1];
            for ($i = $length - 1; $i > 0; $i--) {
                $arr[$i] = $arr[$i - 1];
            }
            $arr[0] = $lastElement;
            return $arr;
        }

        function moveAndReplace($array, $fromIndex, $toIndex)
        {
            $length = count($array);
            $orginVal = $array[$fromIndex];

            // 如果起始位置在目标位置之前
            if ($fromIndex < $toIndex) {
                $startLen = $length - $toIndex - 1;
                $arrStart = array_slice($array, $toIndex + 1, $startLen);
                array_splice($array, $toIndex + 1, $startLen, array_fill(0, $startLen, ''));
                $endLen = $toIndex - $fromIndex + 1;
                $arrEnd = array_slice($array, $fromIndex, $endLen);
                array_splice($array, $fromIndex, $endLen, array_fill(0, $endLen, ''));
            } else { // 如果起始位置在目标位置之后
                $startLen = $length - $fromIndex - 1;
                $arrStart = array_slice($array, $fromIndex + 1, $startLen);
                array_splice($array, $fromIndex + 1, $startLen, array_fill(0, $startLen, ''));
                $endLen = $fromIndex - $toIndex + 1;
                $arrEnd = array_slice($array, $toIndex, $endLen);
                array_splice($array, $toIndex, $endLen, array_fill(0, $endLen, ''));
            }
            $arrOld = array_filter($array, function ($val) {
                return empty($val) ? false : true;
            });
            $newArr = array_merge($arrStart, $arrOld, $arrEnd);
            $newIndex = array_search($orginVal, $newArr);
            while ($newIndex != $toIndex) {
                $newArr = moveNext($newArr);
                $newIndex = array_search($orginVal, $newArr);
            }
            return $newArr;
        }
        
        $array = ['A', 'B', 'C', 'D', 'E'];
        $fromIndex = $params['start']; // A 的位置
        $toIndex = $params['end'];   // C 的位置
        dump(json_encode($array));
        dump("{$array[$fromIndex]} ===> $array[$toIndex]");
        $result = moveAndReplace($array, $fromIndex, $toIndex);
        dump($result);
        die;
    }
相关推荐
李纲明5 小时前
WordPress 后台登录马上被踢回登录页:Cookie 域、HTTPS、盐值和页面缓存怎么查
运维·缓存·https·php·wordpress·cookie
4SAPI5 小时前
AI 数据分析工具大模型 API 选型指南
大数据·人工智能·架构·php·1024程序员节
f8979070706 小时前
php升级之后切换到php8.2.35报pdo错误
php
4SAPI6 小时前
搭建 AI 数据分析工具大模型 API 选型指南
数据库·人工智能·架构·php·1024程序员节
Regentsoft丽晶软件7 小时前
从 “定时拉取“ 到 “事件驱动“,服装库存实时同步的底层架构怎么设计?
经验分享·php·零售
用户60968624266089 小时前
页面构建器做的页面翻译:短代码、区块、动态内容各自会踩什么坑
php·wordpress
阿文和她的Key9 小时前
PHP2Shell事故四层拆解:AI找洞是小时级,披露协调还是邮件级
网络·人工智能·架构·php
贵州诚鑫致达科技有限公司13 小时前
PHP两个9.2分RCE漏洞,速查版本
服务器·php·1024程序员节
hudie76514 小时前
LikeShop 二开最常改的 5 个文件(附改前改后对比)
前端·uni-app·php·个人开发
东宇科技14 小时前
crmeb开源版本安装步骤2026-10-20
后端·php·crmeb