{"id":27076,"date":"2018-01-02T22:09:18","date_gmt":"2018-01-02T16:39:18","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27076"},"modified":"2018-01-02T22:09:18","modified_gmt":"2018-01-02T16:39:18","slug":"c-algorithm-sort-stack-using-recursion","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-algorithm-sort-stack-using-recursion\/","title":{"rendered":"C 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[ad type=&#8221;banner&#8221;]<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<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[ad type=&#8221;banner&#8221;]\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<p><strong><br \/>\nImplementation: <\/strong><br \/>\nBelow is C and Java implementation of above algorithm.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>C Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ C program to sort a stack using recursion<br\/>#include &lt;stdio.h&gt;<br\/>#include &lt;stdlib.h&gt;<br\/> <br\/>\/\/ Stack is represented using linked list<br\/>struct stack<br\/>{<br\/>    int data;<br\/>    struct stack *next;<br\/>};<br\/> <br\/>\/\/ Utility function to initialize stack<br\/>void initStack(struct stack **s)<br\/>{<br\/>    *s = NULL;<br\/>}<br\/> <br\/>\/\/ Utility function to chcek if stack is empty<br\/>int isEmpty(struct stack *s)<br\/>{<br\/>    if (s == NULL)<br\/>        return 1;<br\/>    return 0;<br\/>}<br\/> <br\/>\/\/ Utility function to push an item to stack<br\/>void push(struct stack **s, int x)<br\/>{<br\/>    struct stack *p = (struct stack *)malloc(sizeof(*p));<br\/> <br\/>    if (p == NULL)<br\/>    {<br\/>        fprintf(stderr, &quot;Memory allocation failed.\\n&quot;);<br\/>        return;<br\/>    }<br\/> <br\/>    p-&gt;data = x;<br\/>    p-&gt;next = *s;<br\/>    *s = p;<br\/>}<br\/> <br\/>\/\/ Utility function to remove an item from stack<br\/>int pop(struct stack **s)<br\/>{<br\/>    int x;<br\/>    struct stack *temp;<br\/> <br\/>    x = (*s)-&gt;data;<br\/>    temp = *s;<br\/>    (*s) = (*s)-&gt;next;<br\/>    free(temp);<br\/> <br\/>    return x;<br\/>}<br\/> <br\/>\/\/ Function to find top item<br\/>int top(struct stack *s)<br\/>{<br\/>    return (s-&gt;data);<br\/>}<br\/> <br\/>\/\/ Recursive function to insert an item x in sorted way<br\/>void sortedInsert(struct stack **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 (isEmpty(*s) || x &gt; top(*s))<br\/>    {<br\/>        push(s, x);<br\/>        return;<br\/>    }<br\/> <br\/>    \/\/ If top is greater, remove the top item and recur<br\/>    int temp = pop(s);<br\/>    sortedInsert(s, x);<br\/> <br\/>    \/\/ Put back the top item removed earlier<br\/>    push(s, temp);<br\/>}<br\/> <br\/>\/\/ Function to sort stack<br\/>void sortStack(struct stack **s)<br\/>{<br\/>    \/\/ If stack is not empty<br\/>    if (!isEmpty(*s))<br\/>    {<br\/>        \/\/ Remove the top item<br\/>        int x = pop(s);<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 function to print contents of stack<br\/>void printStack(struct stack *s)<br\/>{<br\/>    while (s)<br\/>    {<br\/>        printf(&quot;%d &quot;, s-&gt;data);<br\/>        s = s-&gt;next;<br\/>    }<br\/>    printf(&quot;\\n&quot;);<br\/>}<br\/> <br\/>\/\/ Driver Program<br\/>int main(void)<br\/>{<br\/>    struct stack *top;<br\/> <br\/>    initStack(&amp;top);<br\/>    push(&amp;top, 30);<br\/>    push(&amp;top, -5);<br\/>    push(&amp;top, 18);<br\/>    push(&amp;top, 14);<br\/>    push(&amp;top, -3);<br\/> <br\/>    printf(&quot;Stack elements before sorting:\\n&quot;);<br\/>    printStack(top);<br\/> <br\/>    sortStack(&amp;top);<br\/>    printf(&quot;\\n\\n&quot;);<br\/> <br\/>    printf(&quot;Stack elements after sorting:\\n&quot;);<br\/>    printStack(top);<br\/> <br\/>    return 0;<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>C Algorithm &#8211; Sort a stack using recursion- 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":[69866,1,73012,79607],"tags":[80224,80704,80703,80225,80705,80702,80780,80223,80222,80779,80221,80227,80706],"class_list":["post-27076","post","type-post","status-publish","format-standard","hentry","category-c-programming","category-coding","category-data-structures","category-stack","tag-c-program-to-reverse-a-stack-without-using-recursion","tag-recursion-explanation-using-stack","tag-recursion-using-stack-example","tag-recursion-using-stack-in-c","tag-recursion-using-stack-in-data-structure","tag-reverse-a-stack-using-recursion","tag-reverse-a-stack-using-recursion-in-java","tag-reverse-stack-c","tag-reverse-stack-using-two-stacks","tag-sort-a-stack-in-ascending-order-using-another-stack","tag-sort-a-stack-using-recursion","tag-sort-a-stack-using-recursion-in-c","tag-sort-stack-java"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27076","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=27076"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27076\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27076"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27076"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27076"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}