-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort-stack.js
More file actions
32 lines (20 loc) · 628 Bytes
/
sort-stack.js
File metadata and controls
32 lines (20 loc) · 628 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// O(n^2) time | O(n) space - where n is the length of the stack
// solution using recursion
function sortStack(stack) {
if (stack.length === 0) return stack;
const top = stack.pop();
sortStack(stack);
insertInSortedOrder(stack, top);
return stack;
}
function insertInSortedOrder(stack, value) {
if (stack.length === 0 || stack[stack.length - 1] <= value) {
stack.push(value);
return;
}
const top = stack.pop();
insertInSortedOrder(stack, value);
stack.push(top);
}
const stack = [-5, 2, -2, 4, 3, 1];
console.log(sortStack(stack));