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;
    }
相关推荐
亿坊电商8 小时前
物联网领域中PHP框架的最佳选择有哪些?
物联网·struts·php
wuzuyu3658 小时前
用php做一个简易的路由
php·路由
老六ip加速器19 小时前
手机ip隔离方法
tcp/ip·智能手机·php
屁股割了还要学20 小时前
【数据结构入门】排序算法(4)归并排序
c语言·数据结构·学习·算法·排序算法
SccTsAxR20 小时前
[C语言]常见排序算法①
c语言·开发语言·经验分享·笔记·其他·排序算法
zstar-_21 小时前
【不背八股】12.十大排序算法
数据结构·算法·排序算法
rockmelodies1 天前
【PHP7内核剖析】-1.3 FPM
php
真正的醒悟1 天前
上网管理行为-ISP路由部署
服务器·php·接口隔离原则
kyle~1 天前
排序---插入排序(Insertion Sort)
c语言·数据结构·c++·算法·排序算法
张晓~183399481211 天前
短视频矩阵源码-视频剪辑+AI智能体开发接入技术分享
c语言·c++·人工智能·矩阵·c#·php·音视频