Data sorting problem

has a sorting requirement that needs to be implemented: the current data moves back N bits or forward N bits. I thought about it for a long time, but I didn"t think of a good solution.

the operation object is a piece of data in the database

hopes to achieve

with the least loss.
Php
Apr.02,2021

The core idea of

is to "cut" the array into several parts according to the original position and the new position, adjust the position and merge again, without involving sorting.
and the scheme I gave can move left or right .

PS. See the title change, the goal is the database, want to cry no tears!

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

/**
i: index
steps: 
inArray: 
*/
function moveStepsInArray(i, steps, inArray) {
    if(i<0 || i>inArray.length - 1 || steps === 0) {
        return inArray;
    }
    var newPosition = i + steps;

    if(newPosition < 0) {
        newPosition = 0;
    }
    if(newPosition > inArray.length - 1) {
        newPosition = inArray.length - 1;
    }

    var front = steps > 0 ? i: newPosition;
    var after = steps > 0 ? newPosition: i;

    var targetVal = inArray[i];

    if(steps > 0) {
        return inArray.slice(0, front)
            .concat(inArray.slice(front + 1, after + 1))
            .concat([targetVal])
            .concat(inArray.slice(after + 1)) 
    }

    if(steps < 0) {
        return inArray.slice(0, front)
            .concat([targetVal])
            .concat(inArray.slice(front, after))
            .concat(inArray.slice(after + 1));
    }
}

moveStepsInArray(4, -3, arr); //arr43

get the position before sorting a , and the position after sorting b ,
if a > b (move forward), just rearrange bmelet a
if a < b (move backward), just rearrange aanthb


js may be handled as follows:


var numArr = [1,2,3,4,5,6,7]
var rotate = function(nums, k) {
    var a = nums.splice(-k,k)
    nums.unshift(...a)
    return nums
}
var rotate2 = function(nums, k) {
    nums.splice(0,0,...nums.splice(-k,k))
    return nums
}
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e679dd-4471d.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e679dd-4471d.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?