Given an array of elements. An element is called as a leader if it is greater than all
the elements to the right of it. Print all the leaders in O(n)?
The following is my approach.Can anyone tell me how to improve the code and also the current time complexity?
Is recursion more efficient in this case?
#include<stdio.h>
void findLeaders(int a[],int n)
{
int i,j=n-1,flag=0;
for(i=0;i<n;i++)
{
if(a[i] > a[i+1])
{
while(a[i]>a[j])
{
if((i+1) ==j)
{
flag=1;
printf("\nleader = %d",a[i]);
break;
}
else j--;
}
j=n-1;
}
}
if(!flag) printf("\nNo leader in the given array\n");
}
int main()
{
int a[100],n=0,i=0;
printf("\nEnter n:");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
findLeaders(a,n);
printf("\n\n");
return 0;
}
Thanks in advance.