import java.util.Stack;
/**
* Recursive Inplace Stack Sorting
* @author Prateek
*/
class SortStack {
//input stack
private Stack<Integer> stack;
public SortStack(Stack<Integer> stack) {
this.stack=stack;
}
/**
* Sorting Subroutine
*/
public void sort(){
if(stack.isEmpty())
return;
int item=stack.pop();
sort();
compareAndPush(item);
}
/**
* Pushing each element of stack by recursion
* @param item: each item of stack which is compared and pushed to stack
*/
public void compareAndPush(int item){
if(stack.isEmpty() || item <= stack.peek())
stack.push(item);
else {
int val=stack.pop();
compareAndPush(item);
stack.push(val);
}
}
public static void main
(String[] args
) {
Stack<Integer> stack= new Stack<Integer>();
stack.push(5);
stack.push(3);
stack.push(1);
stack.push(4);
stack.push(2);
SortStack obj= new SortStack(stack);
obj.sort();
}
}
aW1wb3J0IGphdmEudXRpbC5TdGFjazsKLyoqCiAqIFJlY3Vyc2l2ZSBJbnBsYWNlIFN0YWNrIFNvcnRpbmcgCiAqIEBhdXRob3IgUHJhdGVlawogKi8KY2xhc3MgU29ydFN0YWNrIHsKCgkvL2lucHV0IHN0YWNrCglwcml2YXRlIFN0YWNrPEludGVnZXI+IHN0YWNrOyAKCQoJcHVibGljIFNvcnRTdGFjayhTdGFjazxJbnRlZ2VyPiBzdGFjaykgewoJdGhpcy5zdGFjaz1zdGFjazsKCX0KCQoJLyoqCgkgKiBTb3J0aW5nIFN1YnJvdXRpbmUgCgkgKi8KCXB1YmxpYyB2b2lkIHNvcnQoKXsKCQlpZihzdGFjay5pc0VtcHR5KCkpCgkJCXJldHVybjsKCQkKCQlpbnQgaXRlbT1zdGFjay5wb3AoKTsKCQlzb3J0KCk7CgkJY29tcGFyZUFuZFB1c2goaXRlbSk7Cgl9CgkKCS8qKgoJICogUHVzaGluZyBlYWNoIGVsZW1lbnQgb2Ygc3RhY2sgYnkgcmVjdXJzaW9uCgkgKiBAcGFyYW0gaXRlbTogZWFjaCBpdGVtIG9mIHN0YWNrIHdoaWNoIGlzIGNvbXBhcmVkIGFuZCBwdXNoZWQgdG8gc3R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