xinglie.github.io icon indicating copy to clipboard operation
xinglie.github.io copied to clipboard

数组内移动

Open xinglie opened this issue 1 year ago • 0 comments

let arrayInnerMove = a => {
    for (let end = a.length, last = end - 1, slow = 0, fast = 0, fastNode, moveIndex; slow < end; slow++) {
        let item = a[slow];
        if (item.d) {
            if (fast <= slow) {
                fast = slow + 1;
            }
            while (fast < end) {
                fastNode = a[fast];
                if (!fastNode.d) {
                    break;
                }
                fast++;
            }
            if (fast < end) {
                moveIndex = fast;
                while (moveIndex > slow) {
                    a[moveIndex] = a[moveIndex - 1];
                    moveIndex--;
                }
                a[slow] = fastNode;
                if (fast == last) {
                    break;
                }
            } else {
                break;
            }
        }
    }
};

arrayInnerMove([{ v: 1 }, { d: 1, v: 2 }, { v: 3 }, { d: 1, v: 4 }, { v: 5 }]);
arrayInnerMove([{ v: 1, d: 1 }, { d: 1, v: 2 }, { v: 3 }, { d: 1, v: 4 }, { v: 5 }]);
arrayInnerMove([{ v: 1 }, { v: 2 }, { v: 3 }, { v: 4 }, { v: 5 }]);
arrayInnerMove([{ v: 1 }, { v: 2 }, { v: 3 }, { d: 1, v: 4 }, { d: 1, v: 5 }]);

xinglie avatar Mar 21 '25 09:03 xinglie