
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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 ]
- Related Questions & Answers
- Sorting Array Elements in Javascript
- Clearing the elements of a Stack in Javascript
- Alphanumeric sorting using JavaScript
- Not able to push all elements of a stack into another stack using for loop in JavaScript?
- Sorting odd and even elements separately JavaScript
- Pushing elements to a Stack in Javascript
- Popping elements from a Stack in Javascript
- Peeking elements from a Stack in Javascript
- Topological sorting using Javascript DFS
- Sorting array of exactly three unique repeating elements in JavaScript
- Sorting array according to increasing frequency of elements in JavaScript
- Sorting array based on increasing frequency of elements in JavaScript
- Count unique elements in array without sorting JavaScript
- Prefix calculator using stack in JavaScript
- Implementation of Stack in JavaScript
Advertisements