0% found this document useful (0 votes)
8 views3 pages

Pla Assignment

This document contains 3 code snippets. The first snippet defines a method to find the leaders in an array. The second snippet defines a method to find the majority element in an array. The third snippet defines a method to find the equilibrium index of an array, if one exists.

Uploaded by

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

Pla Assignment

This document contains 3 code snippets. The first snippet defines a method to find the leaders in an array. The second snippet defines a method to find the majority element in an array. The third snippet defines a method to find the equilibrium index of an array, if one exists.

Uploaded by

Pandey Ashmit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Ashmit pandey

21BAI10338 PLA assignment

1)

public static void findLeadersInAnArray(int arr[])


{
System.out.println("Finding leaders in an array : ");
int rightMax=arr[arr.length-1];
// Rightmost will always be a leader
System.out.print(rightMax+" ");
for (int i = arr.length-2; i>=0; i--) {
if(arr[i] > rightMax)
{
rightMax=arr[i];
System.out.print(" "+rightMax);
}
}
}

2)

import java.io.*;

class GFG {
static void findMajority(int arr[], int n)
{
int maxCount = 0;
int index = -1; // sentinels
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j])
count++;
}

if (count > maxCount) {


maxCount = count;
index = i;
}
}

if (maxCount > n / 2)
System.out.println(arr[index]);

else
System.out.println("No Majority Element");
}

public static void main(String[] args)


{
Ashmit pandey
21BAI10338 PLA assignment

int arr[] = { 1, 1, 2, 1, 3, 5, 1 };
int n = arr.length;

// Function calling
findMajority(arr, n);
}
}

3)

class EquilibriumIndex {

int equilibrium(int arr[], int n)

int i, j;

int leftsum, rightsum;

for (i = 0; i < n; ++i) {

leftsum = 0;

for (j = 0; j < i; j++)

leftsum += arr[j];

rightsum = 0;

for (j = i + 1; j < n; j++)

rightsum += arr[j];

if (leftsum == rightsum)

return i;

/* return -1 if no equilibrium index is found */

return -1;

public static void main(String[] args)


Ashmit pandey
21BAI10338 PLA assignment

EquilibriumIndex equi = new EquilibriumIndex();

int arr[] = { -7, 1, 5, 2, -4, 3, 0 };

int arr_size = arr.length;

System.out.println(equi.equilibrium(arr, arr_size));

You might also like