Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Sorting elements of stack using JavaScript
We are required to write a JavaScript function that takes in an array of integers and sorts it using recursion with stack operations (push and pop methods). The function sorts the array in-place without using built-in sorting methods.
How It Works
The algorithm uses two recursive functions:
- sortStack() - Removes elements from the stack and recursively sorts the remaining elements
- sortedInsert() - Inserts an element in its correct position in an already sorted stack
Example
Here's the complete implementation:
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);
}
}
console.log("Original stack:", stack);
sortStack(stack);
console.log("Sorted stack:", stack);
Original stack: [ -3, 14, 18, -5, 30 ] Sorted stack: [ -5, -3, 14, 18, 30 ]
Step-by-Step Process
Let's trace through how the algorithm works with a smaller example:
const smallStack = [3, 1, 4, 2];
const sortStack = (stack = []) => {
if (stack.length > 0) {
let t = stack.pop();
console.log(`Popped: ${t}, Stack: [${stack}]`);
sortStack(stack);
sortedInsert(stack, t);
}
}
const sortedInsert = (stack, e) => {
if (stack.length == 0 || e > stack[stack.length - 1]) {
stack.push(e);
console.log(`Inserted ${e}, Stack: [${stack}]`);
} else {
let x = stack.pop();
sortedInsert(stack, e);
stack.push(x);
}
}
console.log("Starting with:", smallStack);
sortStack(smallStack);
console.log("Final result:", smallStack);
Starting with: [ 3, 1, 4, 2 ] Popped: 2, Stack: [3,1,4] Popped: 4, Stack: [3,1] Popped: 1, Stack: [3] Popped: 3, Stack: [] Inserted 3, Stack: [3] Inserted 1, Stack: [1,3] Inserted 4, Stack: [1,3,4] Inserted 2, Stack: [1,2,3,4] Final result: [ 1, 2, 3, 4 ]
Key Points
- Time Complexity: O(n²) where n is the number of elements
- Space Complexity: O(n) due to recursive call stack
- The algorithm sorts in ascending order
- Uses only basic stack operations (push and pop)
- Modifies the original array in-place
Conclusion
This recursive sorting approach demonstrates how to sort a stack using only basic stack operations. While not the most efficient sorting algorithm, it's an excellent example of recursive problem-solving and stack manipulation techniques.
Advertisements
