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;
    }
相关推荐
梦吉网络6 小时前
悬赏任务系统小程序/APP源码,推荐任务/发布任务/会员服务
php
hweiyu008 小时前
PHP之ThinkPHP5视频教程
php
一枚小小程序员哈8 小时前
基于PHP的快递管理系统的设计与实现
php
蓝黑20208 小时前
PHP的类和魔术方法
php
KoiHeng8 小时前
排序算法(二)
算法·排序算法
秋难降10 小时前
LeetCode——迭代遍历算法
数据结构·算法·排序算法
用户30745969820711 小时前
🌟 PHP 中的 `use` 关键字完全指南
php
啊阿狸不会拉杆11 小时前
《算法导论》第 7 章 - 快速排序
开发语言·数据结构·c++·算法·排序算法
PyHaVolask11 小时前
PHP进阶语法详解:命名空间、类型转换与文件操作
开发语言·php·composer
用户30745969820711 小时前
🌟 PHP 接口(Interface)完全入门指南
php