To find the next greater element in an array

To find the next greater element in an array

Question:

Find the next greater element for each element in the given array.

Logic:

  • First, check for the element which is greater than a[i].
  • If greater element found means stores into a variable m.
  • If any elements greater than a[i] and less than m.
  • Then reassign m with the greater element which is found.
  • Otherwise, it is the largest element of the array and it has no greater elements.
  • Print all the elements with their corresponding greater element.

Program:

[code lang=”c”]
#include<stdio.h>
void main()
{
int a[20],i,j,n,m,l=1;
clrscr();
printf("enter the length:");
scanf("%d",&n);
printf("enter the elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i]<a[j]&&l==1) //checks for the greater element
{
l=0;
m=a[j]; //assign greater element to m
}
else if(a[i]<a[j]&&a[j]<m) //checks for least greater number
{
m=a[j];
}
}
if(l!=1) //next grater element found
{
printf("%d->%d\n",a[i],m);
}
else //when no elements greater than a[i]
{
printf("%d->_\n",a[i]);
}
l=1; //acts as a marker for identifying it as greater element or not
}
getch();
}
[/code]

Alternate way:

An alternate way is to sort all the elements in ascending or descending order then print the next element which is the next greater element.

You might also like:

To find all non-duplicate elements in an array

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.

Leave a Reply

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