How to find next greater element for every element in an array ?

Answer : In an array, to display the Next Greater Element (NGE)…

How to find next greater element for every element in an array ?

  • In an array, to display the Next Greater Element (NGE) for every element.
  • The Next greater Element for an element x is the first greater element on the right side of x value in an array.
  • While the elements for which no greater element exist, consider the next greater element as 0.
 NGE for every element in an array
  • For any array, rightmost element always has next greater element as 0.
  • Next greater element of an array element array[i], is an integer array[j], such that
    • array[i] < array[j]
    • i < j
    • j – i is minimum
  • i.e. array[j] is the first element on the right of array[i] which is greater than array[i].
  • For Example the Input array is 88, 13, 44, 2, 10, 5, 17

Output

Next greater element for 13     = 44
Next greater element for 2      = 10
Next greater element for 5      = 17
Next greater element for 10     = 17
Next greater element for 17     = 0
Next greater element for 44     = 0
Next greater element for 88     = 0

Steps for finding a next greater element

  • To find Next Great Element Using two loops.
  • All the elements one by one to picks in the outer loop.
  • The outer loop picked the first greater element from the inner loop.
  • If a greater element is found then that element is printed as next, otherwise 0 is printed.

Sample Code in Java

[pastacode lang=”java” manual=”class%20Wikitechy%0A%7B%20%0A%09%2F*%20prints%20element%20and%20NGE%20pair%20for%20%0A%09all%20elements%20of%20arr%5B%5D%20of%20size%20n%20*%2F%0A%09static%20void%20printNGE(int%20arr%5B%5D%2C%20int%20n)%20%0A%09%7B%20%0A%09%09int%20n1%2C%20i%2C%20j%3B%20%0A%09%09for%20(i%3D0%3B%20i%3Cn%3B%20i%2B%2B)%20%0A%09%09%7B%20%0A%09%09%09n1%20%3D%200%3B%20%0A%09%09%09for%20(j%20%3D%20i%2B1%3B%20j%3Cn%3B%20j%2B%2B)%20%0A%09%09%09%7B%20%0A%09%09%09%09if%20(arr%5Bi%5D%20%3C%20arr%5Bj%5D)%20%0A%09%09%09%09%7B%20%0A%09%09%09%09%09n1%20%3D%20arr%5Bj%5D%3B%20%0A%09%09%09%09%09break%3B%20%0A%09%09%09%09%7D%20%0A%09%09%09%7D%20%0A%09%09%09System.out.println(arr%5Bi%5D%2B%22%20–%20%22%2Bn1)%3B%20%0A%09%09%7D%20%0A%09%7D%20%0A%09%0A%09public%20static%20void%20main(String%20args%5B%5D)%20%0A%09%7B%20%0A%09%09int%20arr%5B%5D%3D%20%7B30%2C%2035%2C%2011%2C%2017%2C%202%7D%3B%20%0A%09%09int%20n%20%3D%20arr.length%3B%20%0A%09%09printNGE(arr%2C%20n)%3B%0A%20%20%20%20%20%20%20%20%0A%09%7D%20%0A%7D” message=”” highlight=”” provider=”manual”/]

Output

30 -- 35
35 -- 0
11 -- 17
17 -- 0
2 -- 0
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like