Public
Edited
Jun 2, 2023
Insert cell
Insert cell
{
const input = [1, 2, 3, 4];
sortStack(input);
return input;
}
Insert cell
function sortStack(stack) {
const top = stack.pop();
if (top === undefined) {
return; // empty stack is already sorted
}

// sort the rest of the stack
sortStack(stack);

// insert top into the stack at the right place
let helper = [];
let current = stack.pop();
while (current !== undefined && current < top) {
helper.push(current);
current = stack.pop();
}

if (current !== undefined) {
stack.push(current);
current = helper.pop();
}

stack.push(top);
current = helper.pop();
while (current !== undefined) {
stack.push(current);
current = helper.pop();
}
}
Insert cell
{
let stack = [1, 2, 3, 4];
let top = stack.pop();

stack = [3, 2, 1]; // already sorted
let helper = [];
let current = stack.pop();

while (current !== undefined && current < top) {
helper.push(current);
current = stack.pop();
}

if (current !== undefined) {
stack.push(current);
current = helper.pop();
}

stack.push(top);
current = helper.pop();
while (current !== undefined) {
stack.push(current);
current = helper.pop();
}
return { helper, current, stack };
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more