Computer >> Computer tutorials >  >> Programming >> Javascript

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 ]