Skip to content

Commit abf0089

Browse files
committed
Leader.c
1 parent 3d779be commit abf0089

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

DataStructure/Array/Leader.c

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/** Program: A Leader in an array
2+
* For a Leader 'L' all elements on right side of 'L' are lessthen
3+
* 'L'
4+
* Input: arr[] = {15,16,3,2,6,1,4}
5+
* Output:16,6,4
6+
* (Last array element is always a leader since there is no element
7+
* right to last element)
8+
*/
9+
#include<stdio.h>
10+
/* Time complexcity O(n^2) */
11+
void findLeader(int arr[],int n)
12+
{
13+
int i,j;
14+
for(int i=0;i<n;i++)
15+
{
16+
for(j=i+1;j<n;j++)
17+
{
18+
if(arr[j] >= arr[i])
19+
break;
20+
}
21+
if(j == n)
22+
printf("%d is Leader\n",arr[i]);
23+
}
24+
}
25+
26+
/** Efficient method for finding Leader
27+
* Time complexcity O(n)
28+
*/
29+
void findLeader1(int arr[],int n)
30+
{
31+
int end = arr[n-1];
32+
for(int i=n;i>=0;i--)
33+
{
34+
if(arr[i]>=end)
35+
{
36+
end = arr[i];
37+
printf("%d is Leader",end);
38+
printf("\n");
39+
}
40+
}
41+
}
42+
43+
int main()
44+
{
45+
int arr[] = {15,16,3,2,6,1,4};
46+
int n = sizeof(arr)/sizeof(arr[0]);
47+
findLeader(arr,n);
48+
findLeader1(arr,n);
49+
50+
return 0;
51+
}

0 commit comments

Comments
 (0)