-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #76 from samara6855/patch-3
Kth Largest Element using Java
- Loading branch information
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import java.util.Arrays; | ||
import java.util.Scanner; | ||
|
||
public class KthLargest { | ||
|
||
public static int findKthLargest(int[] nums, int k) { | ||
Arrays.sort(nums); | ||
return nums[nums.length - k]; | ||
} | ||
|
||
public static void main(String[] args) { | ||
Scanner scanner = new Scanner(System.in); | ||
|
||
System.out.print("Enter the size of the array: "); | ||
int n = scanner.nextInt(); | ||
|
||
int[] nums = new int[n]; | ||
|
||
System.out.println("Enter " + n + " array elements:"); | ||
for (int i = 0; i < n; i++) { | ||
nums[i] = scanner.nextInt(); | ||
} | ||
|
||
System.out.print("Enter the value of k to find the k'th largest element: "); | ||
int k = scanner.nextInt(); | ||
|
||
System.out.println("The " + k + "th largest element is: " + findKthLargest(nums, k)); | ||
|
||
scanner.close(); | ||
} | ||
} |