Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
The largest element in an array
2.1.
Problem Statement
2.2.
Solutions
3.
Approach 1(Sorting)
3.1.
Algorithm
3.1.1.
Program
3.1.2.
Output
4.
Approach 2(Iterative Method)
4.1.
Algorithm
4.1.1.
Program
4.1.2.
Output
5.
Approach 3(Recursive Method)
5.1.
Program
5.2.
Output
6.
Frequently Asked Questions
7.
Conclusion
Last Updated: Mar 27, 2024

Largest Element in an Array

Author Lekhika
1 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

It's both exciting and powerful to solve difficulties and know that you've developed something that will be useful to someone else. One of the simplest methods to solve practical problems is to code.

Best practices in programming assist you in producing more efficient and effective code.

This article will discuss printing the smallest element in a given array using various Java language methods to enhance your skills in the Java programming language.

Also Read About, Multithreading in java, and Duck Number in Java.

The largest element in an array

An array is a collection of elements of the same kind stored in contiguous memory locations. It may be accessed separately using a unique identifier's index.

A number array, such as an integer array, float array, double array, or long array, can hold numbers of various sizes. In an array, we can discover the largest number of these.

To follow these examples, you need to be familiar with the following Java programming concepts:

  1. Loops in Java
  2. Methods in Java
  3. Concept of Recursion

Problem Statement

Write a programme to discover the largest element in an array arr[] of size n.

Let's consider a small example of an array of 5 elements.

Input: arr[ ] = {32, 57, 63, 55, 48}

Output: 63

Explanation: The largest element of the given array is 63.

Solutions

There are several methods for determining the greatest element. There is support for finding the maximum in the library in every programming language. Internally, though, they are identical. The following are some of the methods that have been discussed.

  • Sorting: Arrange the elements in ascending order, with the last element at the last index.
  • Traverse: Update the maximum value when traversing the array.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Approach 1(Sorting)

Arranging the elements in descending order is a straightforward technique to identify the array's greatest element. After sorting, the largest element will be represented by the first element, the second-largest by the next, and until the last part represents the array's smallest element.

Steps to a Solution

  • Sort the data in the array.
  • Return the element to the array's first index.

Algorithm

  1. Start.
  2. Array Declaration.
  3. Initialization of the array.
  4. To find the largest element in a given array, use two for loops
  5. To hold each element of the array, use the first for loop.
  6. To compare the element to the rest of the elements, use the second for loop.
  7. To sort the elements, swap them around.
  8. Show the element that is the largest.
  9. Exit.

 Here is the Java programme for the Sorting Method:

Program

/*Java Program to find the largest element in an array using Sorting of elements*/
import java.util.Scanner;

class Coding_Ninjas_01
{
    public static void main(String []args)
    {
        Scanner sc=new Scanner(System.in);
        int r;     //Declaring the size of the array
        System.out.println("Enter the size of your array");
        r=sc.nextInt();   //Initialise array size

        int arr[]=new int[r];   //Declaring the array 
        System.out.println("Enter your array");  
        for(int i=0;i<r;i++)     //Initialising the array
        {
            arr[i]=sc.nextInt();
        }
        for(int i=0;i<r;i++)   //Use to hold an element of the given array.
        {
            for(int j=i+1;j<r;j++)   //Use to check for rest of the elements of the array
            {
                if(arr[i]<arr[j])    //Comparing and swapping
                {
                    int temp=arr[i];
                    arr[i]=arr[j];
                    arr[j]=temp;
                }
            }
        }
        
        System.out.println("The Largest element of the given array is "+arr[0]);  //Display the Largest after sorting
        
    }

Output

Enter the size of the array 5
Enter the array 32 57 63 55 48
The Largest element of the given array is 63

Time complexity: O(N2) where there are N elements in the array

Space complexity: O(1)

Approach 2(Iterative Method)

This program aims to discover the largest element in the array. This can be done by keeping a variable called large, which will initially retain the value of the first element. By comparing the value of ‘large’ with the array's items, you may loop across the array. If any element's values are more than large, the element's value is stored in large.

Algorithm

  • Declare a variable called large and set its value to the first entry of the array.
  • Check each index from 1 to n(size of the array) in a loop.
  • Set large = arr[i] if arr[i]>large.
  • Print the largest number after completing all iterations.

Here is the Java Program for the Iterative method:

Program

public class Coding_Ninjas_02 {  
    public static void main(String[] args) {  
  
        //Initialise array  
        int [] arr = new int [] {32, 57, 63, 55, 48};  
        //Initialise large with first element of array.  
        int large = arr[0];  
        //Loop through the array  
        for (int i = 0; i < arr.length; i++) {  
            //Compare elements of array with large
          if(arr[i] >large)  
              large = arr[i];  
        }  
        System.out.println("The largest element in the given array: " + large);  
    }  
}

Output

The largest element in the given array: 63

Time complexity: O(N) where there are N elements in the array

Space complexity: O(1)

Learn more: Array in Java

Approach 3(Recursive Method)

The Top-down Recursive approach mainly consists of three steps:

  1. Creation of a Recursive Function: Construct a recursive function with the name getmin (int arr[], int num)
  2. Deciding a base condition: If (num==1) is true, return arr[0]
  3. Otherwise condition: Return max(arr[num-1], getmax(arr, num-1)) if base condition is not true.
     

Here is the Recursive program to find the largest element of the given array.

Program

// Recursive Java program to find maximum
import java.util.*;

class Coding_Ninjas_03 {
// Recursive function to return maximum element using recursion
public static int findlarge(int arr[], int num)
{
// if num== 1 means we have only one element
if(num == 1)
return arr[0];

return Math.max(arr[num-1], findlarge(arr, num-1));
}

// Driver code
public static void main(String args[])
{
int arr[] = {52, 47, 63, 55, 48};
int num = arr.length;

// Calling Recursive Function
System.out.println(findlarge(arr, num));
}
}

Output

63

 

Try it by yourself on java online compiler.

Also check out Addition of Two Numbers in Java here.

Frequently Asked Questions

  1. How to declare an array in Java?
    In Java, you may declare an array in the following way:
    dataType[]    arrayVariableName  = new dataType[arraySize];
    You may declare an int array as follows for the int data type:
    int[]  temp = new int[20];
     
  2. Can we resize the array in Java after creation?
    We can't adjust the size of an array after it's been created. On the other hand, other data structures can alter in size after being created.
     
  3. Can we pass a negative number as the size of the array?
    No, a negative value cannot be used as an Array size. We won't get a compile-time error if we use a negative number for Array size. Instead, the NegativeArraySizeException will be thrown at runtime.
     
  4. What's the distinction between an ArrayStoreException and an ArrayOutOfBoundsException?
    If you try to add an incompatible data type, an ArrayStoreException is produced. For example, if you try to add an integer object to a String Array, you'll get an ArrayStoreException.

    When an attempt is made to access an Array with an illegal index, an ArrayOutOfBoundsException is issued. For instance, an illegal index is either negative or bigger than or equal to the Array's size.
     
  5. In Java, what is an Anonymous Array?
    Anonymous Arrays are arrays that have no name (or reference). They're helpful in situations where we just need to use Array once. As an example,
    Anonymous int array: new int[] {3, 4, 2, 8, 9};

Conclusion

This article has discussed the Java Program to find the largest element of a given array using the Sorting method, iterative and Recursive Methods.

We hope this article has helped you. You can also learn Object-Oriented Properties of Java, such as  Abstraction in javaInheritance in Java. You can also learn about the properties like association, aggregation,  composition, and many more.

Recommended problems -

 

Visit Coding Ninjas Studio, our practice platform, to practise top problems, take mock tests, read interview experiences, and do more technical stuff.

We wish you Good Luck! Keep coding and keep reading Ninja!!

 

Previous article
Program to Print the Elements of an Array
Next article
Smallest Element in an Array
Live masterclass