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;
    }
相关推荐
海天鹰14 小时前
PHP上传文件
android·开发语言·php
王老师青少年编程16 小时前
csp信奥赛C++高频考点专项训练:【排序算法】案例7:最高分数的学生姓名
c++·排序算法·csp·高频考点·信奥赛·最高分数的学生姓名
shiyi.十一17 小时前
第7章:无线网络和移动网络 — 知识要点与架构
网络·架构·php
晓梦林18 小时前
[极客大挑战 2019]PHP学习笔记
笔记·学习·php
2401_8949155318 小时前
Geo优化系统源码部署搭建技术——PHP程序开发部署指南
开发语言·php
HH‘HH21 小时前
前端应用的离线暂停更新策略:原理、实现与最佳实践
开发语言·前端·php
xlq223221 天前
高并发服务器day8(含服务器完整架构)
运维·服务器·php
Loongproxy1 天前
2026年隧道带IP哪个好?国内代理IP服务商排名:高匿、稳定、性价比对比
网络·tcp/ip·php
twcc_come2 天前
安全策略配置实验报告
开发语言·php
weixin_BYSJ19872 天前
springboot3家政平台小程序--附源码00904
java·javascript·spring boot·python·django·flask·php