0% found this document useful (0 votes)
37 views1 page

Find Leaders in an Array Code

The document describes a method to find leaders in an array, where a leader is defined as an element that is greater than all elements to its right. The last element is always considered a leader, and the algorithm iterates through the array from the second last element to the first, updating and printing leaders as it finds them. A sample implementation in Java is provided to demonstrate the concept.

Uploaded by

Kaushal Bhatt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views1 page

Find Leaders in an Array Code

The document describes a method to find leaders in an array, where a leader is defined as an element that is greater than all elements to its right. The last element is always considered a leader, and the algorithm iterates through the array from the second last element to the first, updating and printing leaders as it finds them. A sample implementation in Java is provided to demonstrate the concept.

Uploaded by

Kaushal Bhatt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

leaders in array

L = last element
print L

for i = n-2 to 0
if array[i] > L
L = array[i]
print L

Suppose we have to check if 8 is greater than {0,3,5}. Normally we will check if 8


is greater than 0/3/5 individually. We can also do it quickly. All we need to do is
just find the maximum of {0,3,5} i.e. 5 and compare only 5 with 8.

We just need to check if an element of an array is greater than the maximum element
among all the elements to its right.

We will make a variable. Let's name it leader (L) and assign it the last element of
the array as it is a leader by default.

class Ideone {

// function for finding leaders


public static void leaderprint(int arr[], int n) {

// last element of an array is leader by default


int L = arr[n - 1];
System.out.println(L + " is a leader");

// for finding leaders in other elements of the array


for (int i = n - 2; i >= 0; i--)
{
if (arr[i] > L)
{
L = arr[i];
System.out.println(L + " is a leader");
}
}
}

public static void main(String[] args)


{
int[] arr = { 7, 6, 4, 5, 0, 1 };
int n = arr.length;

leaderprint(arr, n);
}
}

You might also like