Sorting Elements Of Stack Using Javascript
I m trying to understand sorting a stack elements using recursion given in http://www.geeksforgeeks.org/sort-a-stack-using-recursion/ Use of any loop constructs like while, for..e
Solution 1:
With javascript, local (scoped) variables need to be declared as var, otherwise they are static. Without the var before t in sortStack(), t would be a static and just get overwritten with each pop, leaving t == -3 on all the returns from sortStack(). The same issue occurs with x in sortedInsert().
var stack = [-3, 14, 18, -5, 30];
functionsortStack(s) {
if (s.length > 0) {
var t = s.pop();
sortStack(s);
sortedInsert(s, t);
}
}
functionsortedInsert(s, e) {
if (s.length == 0 || e > s[s.length - 1]) {
s.push(e);
} else {
var x = s.pop();
sortedInsert(s, e);
s.push(x);
}
}
sortStack(stack);
console.log(stack);
Solution 2:
If you just want to sort the array, you can use sort()
method. Check example below:
var stack = [-3, 14, 18, -5, 30];
console.log(stack.sort());
If you want to understand how to sort array manually, have a look at this ans (Note: below code is copied from same ans):
var stack = [-3, 14, 18, -5, 30];
functionarrSort(arr, subkey) {
//Default to 0 if no subkey is set
subkey = (subkey === undefined ? 0 : subkey);
var a = arr.slice(0),
b = [], x;
// For each section in the array, create an array containing whatever we are trying to sort by and our unique IDfor (x in a) {
b[x] = [a[x][subkey], x];
}
b = b.sort();
//Wipe out all the data that's currently in arr!
arr.splice(0, arr.length);
for (x in b) {
arr.push(a[b[x][1]]);
}
return arr;
}
// console.log(arrSort(stack, 0));console.log(arrSort(stack));
Solution 3:
var stack = [-3, 14, 18, -5, 30];
functioncompare(a,b) {
returnparseInt(a, 10) - parseInt(b, 10);
}
stack.sort(compare);
console.log(stack);
Solution 4:
/*
Create a temporary stack say tmpStack.
While input stack is NOT empty do this:
Pop an element from input stack call it temp
while temporary stack is NOT empty and top of temporary stack is greater than temp,
pop from temporary stack and push it to the input stack
push temp in temporary stack
The sorted numbers are in tmpStack
*/classsortStack{
constructor(){
this.tempStack = [];
}
sortStack(inputStack){
if(inputStack.length==0){
return"empty "
}
while(inputStack.length > 0){
let item = inputStack.pop()
while(this.tempStack.length > 0 && item < this.tempStack[this.tempStack.length -1]){
inputStack.push(this.tempStack.pop())
}
this.tempStack.push(item)
}
returnthis.tempStack;
}
}
let a = [34, 3, 31, 98, 92, 23];
let s = newsortStack();
console.log(s.sortStack(a))
Post a Comment for "Sorting Elements Of Stack Using Javascript"