This is the Java program to print all the leaders in an array.
Given an array of integers, find and print all the leaders of the array. A leader is defined as an element of the array which is greater than all the elements following it. The rightmost element is always a leader.
For example:
In the array {8, 7, 4, 3, 5, 2}, leaders are 8, 7, 5 and 2.
Explanation:
8 > 7, 8 > 4, 8 > 3, 8 > 5, 8 > 2.
7 > 4, 7 > 3, 7 > 5, 7 > 2.
5 > 2.
2 is the rightmost element.
The idea is to traverse the array from right to left and keep track of the maximum element encountered. If the maximum element changes, then that element is a leader of the array.
Here is the source code of the Java Program to print all the leaders of an array. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
// Java program to print all the leaders in an array.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class LeaderInAnArray {
//The main function to take input from the user
//and display the leaders in an array
public static void main(String[] args) {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int size;
System.out.println("Enter the size of the array");
try{
size=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println("Invalid Input");
return;
}
int[] array=new int[size];
System.out.println("Enter array elements");
int i;
for(i=0;i<array.length;i++){
try{
array[i]=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println("An error occurred. Exiting");
return;
}
}
System.out.println("The leaders of the array are");
\\ max variable is used to keep track of the current maximum element
int max=Integer.MIN_VALUE;
\\ loop to print all the leaders of the array
for(i=array.length-1;i>=0;i--) {
if (array[i] > max) {
System.out.print(array[i] + " ");
max = array[i];
}
}
}
}
1. In function main(), firstly the user enters the array.
2. The variable max is initialized to Integer.MIN_VALUE.
3. The loop for(i=array.length-1;i>=0;i–) iterates through the array from right to left.
4. If any element, greater than max is found, then that element is displayed and the max variable is set to array[i].
Time Complexity: O(n) where n is the number of elements in the array.
Case 1 (Simple Test Case): Enter the size of the array 6 Enter array elements 8 7 4 3 5 2 The leaders of the array are 2 5 7 8 Case 2 (Simple Test Case - reverse sorted array): Enter the size of the array 10 Enter array elements 9 8 7 6 5 4 3 2 1 0 The leaders of the array are 0 1 2 3 4 5 6 7 8 9 Case 3 (Simple Test Case - sorted array): Enter the size of the array 5 Enter array elements 1 2 3 4 5 The leaders of the array are 5
Sanfoundry Global Education & Learning Series – Java Programs.
- Practice Information Technology MCQs
- Apply for Computer Science Internship
- Practice Programming MCQs
- Check Java Books
- Apply for Java Internship