Java program to find the largest number in an array


To find the largest element of the given array, first of all, sort the array.

Sorting an array

  • Compare the first two elements of the array
  • If the first element is greater than the second swap them.
  • Then, compare 2nd and 3rd elements if the second element is greater than the 3rd swap them.
  • Repeat this till the end of the array.

After sorting an array print the 1st element from the end of the array.

Example

Live Demo

public class ThirdLargestNumberInAnArray {
   public static void main(String args[]){
      int temp, size;
      int array[] = {10, 20, 25, 63, 96, 57};
      size = array.length;

      for(int i = 0; i<size; i++ ){
         for(int j = i+1; j<size; j++){
            if(array[i]>array[j]){
               temp = array[i];
               array[i] = array[j];
               array[j] = temp;
            }
         }
      }
      System.out.println("Third largest element is:: "+array[size-1]);
   }
}

Output

Third largest element is:: 96

Another solution

You can also sort the elements of the given array using the sort method of the java.util.Arrays class then, print the 1st element from the end of the array.

Example

Live Demo

import java.util.Arrays;
public class LargestNumberSample {
   public static void main(String args[]){
      int array[] = {10, 20, 25, 63, 96, 57};
      int size = array.length;
      Arrays.sort(array);
      System.out.println("sorted Array ::"+Arrays.toString(array));
      int res = array[size-1];
      System.out.println("largest element is ::"+res);
   }
}

Output

sorted Array ::[10, 20, 25, 57, 63, 96]
largest element is ::96

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 13-Mar-2020

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements