Pattern visualizer
Rearrange Array Elements by Sign
The output shape is fixed before a single value is read: even slots must hold positives, odd slots must hold negatives. So the sign of an element already tells you which slot family it belongs to, and the only question left is which slot in that family — always the next unused one. Two cursors answer that: pos starts at 0, neg starts at 1, and each advances by 2 after a write, so they walk disjoint parities and can never overwrite each other. Scanning the input left to right and appending into the matching cursor preserves relative order automatically, because neither cursor ever moves backwards. One pass, one write per element, and no sorting. Animated on: nums = [3, 1, -2, -5, 2, -4, -1, 6] holds equal counts of positives and negatives. Rebuild it so the signs alternate starting with a positive, keeping the relative order within each sign. Answer: [3, -2, 1, -5, 2, -4, 6, -1]..
Two write cursors stepping by two
The answer has to alternate starting positive, so slot parity already decides every sign: even slots 0, 2, 4... are positive and odd slots 1, 3, 5... are negative. That means no sorting and no comparing — just two write cursors, pos=0 on the first even slot and neg=1 on the first odd slot, each jumping two at a time so it never lands on the other's parity.
1FUNCTION rearrangeBySign(nums)2 out <- ARRAY OF LENGTH(nums)3 pos <- 04 neg <- 15 FOR i <- 0 TO LENGTH(nums) - 16 IF nums[i] > 07 out[pos] <- nums[i]8 pos <- pos + 29 ELSE10 out[neg] <- nums[i]11 neg <- neg + 212 RETURN out
← / → step · space play · Home restart