Sunday, 31 May 2015

Next Greater Element

/// PRINT NEXT GREATER ELEMENT IN THE STACK FOR AN ARRAY O(N)
void printNextGreater( int arr[] ,int n )
{
    // the array item under consideration
    int next  ;
    int element ; //the current popped element
    struct stack s;
   
    //push the first element to the stack
    s.push(&s , arr[0]) ;
   
    for(int  i = 1 ; i < n ; ++i)
    {
        next = i ;
   
            while( isEmpty(s) == false )
            {
                //pop the element from the stack
                element = s.pop();
               
                //print the pairs until popped element are smaller than next
                // these are the next greater element pairs for each element in stack pushed earlier
                while ( element < next)
                {
                    printf("%d -> %d \n" , element , next );
                    if(isEmpty(s)) break;
                    element = pop(&s);
                }
               
                //if the popped element is greater than next , push it back to stack
                if(element > next )
                    push(&s , element);
               
            }
           
            //push the next to find its next greater element
            push (&s , next);
   
    }
   
    //for all remaining element in the stack , print -1 as these elements dont have next greater element
    while(isEmpty(s) == false)
    {
        printf("%d -> -1" , pop(&s));
    }
   
}

No comments:

Post a Comment