Workspace Rearrange Array By Sign
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Rearrange Array by Sign visualizer

Learn Rearrange Array by Sign with a step-by-step Arrays visualizer, JavaScript source code and a worked example. Practice optimization and matrix.

INTERACTIVE EXECUTION STUDIO
LEARN BY DOING

Predict. Execute. Understand.

Follow the source code, inspect live state changes, and predict the next operation before revealing it.

1 / 7Execution step
Reference example · JavaScript
Inspect reference input
[
  3,
  1,
  -2,
  -5,
  2,
  -4
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
let p=0,n=1,o=Array(a.length).fill(null);
a.forEach((x,i)=>{
if(x>=0){
o[p]=x;
p+=2
}else{
o[n]=x;
n+=2
}
s("Place by sign",{
Array:a,Output:o
},[i])
});
return o
};

Execution canvas

Active Changed
STEP 1

Place by sign

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Array6 items
Output6 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Arrays · Optimization and matrix

Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.

Example input

[
  3,
  1,
  -2,
  -5,
  2,
  -4
]

Execution steps

  1. Place by sign

Computed output

[
  3,
  -2,
  1,
  -5,
  2,
  -4
]
JavaScript reference implementation
const solve = (a,s)=>{
  let p=0,n=1,o=Array(a.length).fill(null);
  a.forEach((x,i)=>{
    if(x>=0){
      o[p]=x;
      p+=2
    }else{
      o[n]=x;
      n+=2
    }
    s("Place by sign",{
      Array:a,Output:o
    },[i])
  });
  return o
};

Continue learning

Practice related DSA questions in the same topic.