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;
    }
相关推荐
阿Y加油吧3 小时前
力扣打卡——盛最多水的容器、三数之和
算法·leetcode·排序算法
Barkamin3 小时前
快速排序非递归实现
java·算法·排序算法
牢七3 小时前
PHP Debug配置记录
开发语言·php
像污秽一样3 小时前
算法设计与分析-习题8.2
数据结构·算法·排序算法·dfs·化简
像污秽一样4 小时前
算法设计与分析-习题4.3
数据结构·算法·排序算法
NGC_66116 小时前
TCP可靠传输怎么实现的
服务器·网络·php
catchadmin7 小时前
告别阻塞!用 PHP TrueAsync 实现 PHP 脚本提速 10 倍
开发语言·php
00后初来乍到8 小时前
Docker 搭建 LNMP(Nginx+PHP+MySQL)完整踩坑实录
nginx·docker·php
中科三方8 小时前
域名管理常见问题:添加域名解析多久生效?为什么不能马上生效?
开发语言·php
卤炖阑尾炎9 小时前
LNMP/LNAMP 架构部署实战:从环境搭建到 Discuz 论坛与动静分离实现
架构·php