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;
    }
相关推荐
yangSnowy15 小时前
webman框架虚拟数据填充fakerphp/faker插件的使用
php
简鹿视频17 小时前
视频转mp4格式具体作步骤
ffmpeg·php·音视频·实时音视频
liebe1*117 小时前
第十一章 密码学
服务器·密码学·php
一分半心动19 小时前
lnmp架构 mysql数据库Cannot assign requested address报错解决
linux·mysql·php
Han.miracle20 小时前
数据结构与算法--007三数之和(medium)
算法·leetcode·排序算法
catchadmin1 天前
PHP 开发者指南 如何在 Composer 中使用本地包
开发语言·php·composer
刘孬孬沉迷学习1 天前
GTP协议
开发语言·学习·5g·php·信息与通信
C+++Python1 天前
PHP 反射 API
android·java·php
bleach-1 天前
buuctf系列解题思路祥讲--[网鼎杯 2020 青龙组]AreUSerialz1——文件包含漏洞,PHP代码审计,php伪协议,php反序列化
开发语言·安全·web安全·网络安全·渗透测试·php
又是忙碌的一天1 天前
八大排序之:冒泡排序、快速排序和堆排序
数据结构·算法·排序算法