- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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