Sorting elements of stack using JavaScript


We are required to write a JavaScript function that takes in an array of Integers. Making use of recursion and the push and pop methods of the array, the function should sort the array inplace.

Example

The code for this will be −

const stack = [−3, 14, 18, −5, 30];
const sortStack = (stack = []) => {
   if (stack.length > 0) {
      let t = stack.pop();
      sortStack(stack);
      sortedInsert(stack, t);
   };
}
const sortedInsert = (stack, e) => {
   if (stack.length == 0 || e > stack[stack.length − 1]) {
      stack.push(e);
   } else {
      let x = stack.pop();
      sortedInsert(stack, e);
      stack.push(x);
   }
}
sortStack(stack);
console.log(stack);

Output

And the output in the console will be −

[ −5, −3, 14, 18, 30 ]

Updated on: 23-Nov-2020

187 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements