Posts

Showing posts from January, 2015

Java program to get the Next Greater Element in an array

Hi Everyone, it's been a long time since I have made a post. So here goes one. In this blog post, I will be writing about a Java program to get the next greater element in an array. Expected output : For every element in the array, print the number which is the next greater to the element and which occurs after the element in position. If greater element is not found print -1. Logic of the program : Assign an element next greater value, " ngv "as -1. For every element " i " in the array, loop from the next element till last element. In the loop, if an element is greater than " i " and " ngv " is -1 , assign " ngv " as the element. In the loop, if an element is greater than " i " and " ngv " is not -1, check whether " ngv " greater than that element. If so, assign " ngv " as the element. Return " ngv ". The java program is as follows: package  com.blog.techjourney;