 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ]
Advertisements
 