How to find Nth largest number in an array

This is the first solution to find the Nth largest number from an array of given numbers. This program uses the sort method of the Arrays class.

import java.util.Arrays;
import java.util.Scanner;

public class Nthlargest {

	public static void main(String[] args) {

		// Initialized the Array numbers
		int [] numArray= new int[] {34,21,45,75,62,98,13,49};

		System.out.println("The given array numbers are here");
		System.out.print("[");

		//Print the Array elements to the console
		dispArray(numArray);
		Scanner inpInt=new Scanner(System.in);
		System.out.println("Which Nth largest number ?=");
		int nthLargest=inpInt.nextInt();

		//Sort the array, and provide right subscript to fetch Nth largest
		Arrays.sort(numArray);
		System.out.println("The "+nthLargest+"th largest number is="+numArray[numArray.length-nthLargest]);
		
		inpInt.close();
	}

	//The dispArray function with the argument Array
	private static void dispArray(int[] numArray) {
		// TODO Auto-generated method stub
		for(int i=0;i<numArray.length;i++) {
			System.out.print(numArray[i]+" ");
		}
		System.out.println("]");
	}
}
OUTPUT:
The given array numbers are here
[34 21 45 75 62 98 13 49 ]
Which Nth largest number ?=
5
The 5th largest number is=45

Comments

One response to “How to find Nth largest number in an array”

  1. I blog frequently and I seriously thank you for your information. This article has truly peaked my interest. I am going to bookmark your website and keep checking for new details about once a week. I subscribed to your RSS feed too.

    Like

Leave a reply to Paulina Boadway Cancel reply