{"id":27077,"date":"2018-01-02T22:15:18","date_gmt":"2018-01-02T16:45:18","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27077"},"modified":"2018-01-02T22:15:18","modified_gmt":"2018-01-02T16:45:18","slug":"java-algorithm-sort-stack-using-recursion","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-algorithm-sort-stack-using-recursion\/","title":{"rendered":"Java Algorithm &#8211; Sort a stack using recursion"},"content":{"rendered":"<p>Given a stack, sort it using recursion. Use of any loop constructs like while, for..etc is not allowed. We can only use the following ADT functions on Stack S:<span id=\"more-135684\"><\/span><\/p>\n<pre>is_empty(S)  : Tests whether stack is empty or not.\r\npush(S)\t     : Adds new element to the stack.\r\npop(S)\t     : Removes top element from the stack.\r\ntop(S)\t     : Returns value of the top element. Note that this\r\n               function does not remove element from the stack.<\/pre>\n<p>Example:<\/p>\n<pre>Input:  -3  &lt;--- Top\r\n        14 \r\n        18 \r\n        -5 \r\n        30 \r\n\r\nOutput: 30  &lt;--- Top\r\n        18 \r\n        14 \r\n        -3 \r\n        -5<\/pre>\n<p><b>We strongly recommend you to minimize your browser and try this yourself first.<\/b><br \/>\nThis problem is mainly a variant of Reverse stack using recursion.<\/p>\n<p>The idea of the solution is to hold all values in Function Call Stack until the stack becomes empty. When the stack becomes empty, insert all held items one by one in sorted order. Here sorted order is important.<\/p>\n[ad type=&#8221;banner&#8221;]<strong><br \/>\nAlgorithm<\/strong><br \/>\nWe can use below algorithm to sort stack elements:<\/p>\n<pre>sortStack(stack S)\r\n\tif stack is not empty:\r\n\t\ttemp = pop(S);  \r\n\t\tsortStack(S); \r\n\t\tsortedInsert(S, temp);\r\n<\/pre>\n<p>Below algorithm is to insert element is sorted order:<\/p>\n<pre>sortedInsert(Stack S, element)\r\n\tif stack is empty OR element &gt; top element\r\n\t\tpush(S, elem)\r\n\telse\r\n\t\ttemp = pop(S)\r\n\t\tsortedInsert(S, element)\r\n\t\tpush(S, temp)\r\n<\/pre>\n<p><strong><br \/>\nIllustration:<\/strong><\/p>\n<pre>Let given stack be\r\n-3\t&lt;-- top of the stack\r\n14\r\n18\r\n-5\r\n30<\/pre>\n<p>Let us illustrate sorting of stack using above example:<\/p>\n<p>First pop all the elements from the stack and store poped element in variable &#8216;temp&#8217;. After poping all the elements function&#8217;s stack frame will look like:<\/p>\n<pre>temp = -3\t--&gt; stack frame #1\r\ntemp = 14\t--&gt; stack frame #2\r\ntemp = 18\t--&gt; stack frame #3\r\ntemp = -5\t--&gt; stack frame #4\r\ntemp = 30       --&gt; stack frame #5<\/pre>\n<p>Now stack is empty and &#8216;insert_in_sorted_order()&#8217; function is called and it inserts 30 (from stack frame #5) at the bottom of the stack. Now stack looks like below:<\/p>\n<pre><span style=\"color: red;\"><b>30<\/b><\/span>\t&lt;-- top of the stack<\/pre>\n<p>Now next element i.e. -5 (from stack frame #4) is picked. Since -5 &lt; 30, -5 is inserted at the bottom of stack. Now stack becomes:<\/p>\n<pre>30\t&lt;-- top of the stack\r\n<span style=\"color: red;\">-<b>5<\/b><\/span><\/pre>\n[ad type=&#8221;banner&#8221;]\n<p>Next 18 (from stack frame #3) is picked. Since 18 &lt; 30, 18 is inserted below 30. Now stack becomes:<\/p>\n<pre>30\t&lt;-- top of the stack\r\n<span style=\"color: red;\"><b>18<\/b><\/span>\t\r\n-5<\/pre>\n<p>Next 14 (from stack frame #2) is picked. Since 14 &lt; 30 and 14 &lt; 18, it is inserted below 18. Now stack becomes:<\/p>\n<pre>30\t&lt;-- top of the stack\r\n18\r\n<span style=\"color: red;\"><b>14<\/b><\/span>\t\r\n-5<\/pre>\n<p>Now -3 (from stack frame #1) is picked, as -3 &lt; 30 and -3 &lt; 18 and -3 &lt; 14, it is inserted below 14. Now stack becomes:<\/p>\n<pre>30\t&lt;-- top of the stack\r\n18\r\n14\r\n<b><span style=\"color: red;\">-3<\/span><\/b>\t\r\n-5<\/pre>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Implementation: <\/strong><br \/>\nBelow is C and Java implementation of above algorithm.<\/p>\n<p><strong>Java Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program to sort a Stack using recursion<br\/>\/\/ Note that here predefined Stack class is used<br\/>\/\/ for stack operation<br\/> <br\/>import java.util.ListIterator;<br\/>import java.util.Stack;<br\/> <br\/>class Test<br\/>{<br\/>    \/\/ Recursive Method to insert an item x in sorted way<br\/>    static void sortedInsert(Stack&lt;Integer&gt; s, int x)<br\/>    {<br\/>        \/\/ Base case: Either stack is empty or newly inserted<br\/>        \/\/ item is greater than top (more than all existing)<br\/>        if (s.isEmpty() || x &gt; s.peek())<br\/>        {<br\/>            s.push(x);<br\/>            return;<br\/>        }<br\/>      <br\/>        \/\/ If top is greater, remove the top item and recur<br\/>        int temp = s.pop();<br\/>        sortedInsert(s, x);<br\/>      <br\/>        \/\/ Put back the top item removed earlier<br\/>        s.push(temp);<br\/>    }<br\/>      <br\/>    \/\/ Method to sort stack<br\/>    static void sortStack(Stack&lt;Integer&gt; s)<br\/>    {<br\/>        \/\/ If stack is not empty<br\/>        if (!s.isEmpty())<br\/>        {<br\/>            \/\/ Remove the top item<br\/>            int x = s.pop();<br\/>      <br\/>            \/\/ Sort remaining stack<br\/>            sortStack(s);<br\/>      <br\/>            \/\/ Push the top item back in sorted stack<br\/>            sortedInsert(s, x);<br\/>        }<br\/>    }<br\/>     <br\/>    \/\/ Utility Method to print contents of stack<br\/>    static void printStack(Stack&lt;Integer&gt; s)<br\/>    {<br\/>       ListIterator&lt;Integer&gt; lt = s.listIterator();<br\/>        <br\/>       \/\/ forwarding<br\/>       while(lt.hasNext())<br\/>           lt.next();<br\/>        <br\/>       \/\/ printing from top to bottom<br\/>       while(lt.hasPrevious())<br\/>           System.out.print(lt.previous()+&quot; &quot;);<br\/>    }<br\/>   <br\/>    \/\/ Driver method <br\/>    public static void main(String[] args) <br\/>    {<br\/>        Stack&lt;Integer&gt; s = new Stack&lt;&gt;();<br\/>        s.push(30);<br\/>        s.push(-5);<br\/>        s.push(18);<br\/>        s.push(14);<br\/>        s.push(-3);<br\/>      <br\/>        System.out.println(&quot;Stack elements before sorting: &quot;);<br\/>        printStack(s);<br\/>      <br\/>        sortStack(s);<br\/>      <br\/>        System.out.println(&quot; \\n\\nStack elements after sorting:&quot;);<br\/>        printStack(s);<br\/>      <br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Stack elements before sorting:\r\n-3 14 18 -5 30 \r\n\r\nStack elements after sorting:\r\n30 18 14 -3 -5<\/pre>\n<p><strong>Exercise:<\/strong> Modify above code to reverse stack in descending order.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Algorithm &#8211; Sort a stack using recursion &#8211; Data Structure &#8211; Given a stack, sort it using recursion. Use of any loop constructs like while, for..etc<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73012,79607],"tags":[80793,80703,80702,80792,80779,80795,80791,80796,80794],"class_list":["post-27077","post","type-post","status-publish","format-standard","hentry","category-data-structures","category-stack","tag-how-to-sort-a-stack-using-a-temporary-stack","tag-recursion-using-stack-example","tag-reverse-a-stack-using-recursion","tag-sort-a-stack-in-ascending-order-java","tag-sort-a-stack-in-ascending-order-using-another-stack","tag-sort-a-stack-using-another-stack-java","tag-sort-a-stack-using-recursion-java","tag-sort-stack-c","tag-write-a-program-to-sort-a-stack-in-ascending-order"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27077","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27077"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27077\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27077"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27077"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27077"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}