Problem statement:
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the nth largest element in the array.
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the nth largest element in the array.
- public class NthLargestElement {
- public static void main(String[] args) {
- int a[] = { 3, 4, 1, 105, 10, -10 };
- int thirdLargest = 3;
- int max = nthLargestElement(a, thirdLargest);
- System.out.println(max);
- }
- public static int nthLargestElement(int a[], int n) {
- // Sort the given array
- Arrays.sort(a);
- // Return n'th element in the sorted array
- return a[a.length - n];
- }
- }
Output:
4
No comments:
Post a Comment