From 8fd68a5299b20740c9adddedaa413f77565f8e43 Mon Sep 17 00:00:00 2001 From: Ritesh jha <111743207+ritesh123git@users.noreply.github.com> Date: Tue, 3 Oct 2023 23:47:00 +0530 Subject: [PATCH] Create ritesh.java --- .../ritesh.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Find the Kth largest and Kth smallest number in an array/ritesh.java diff --git a/Find the Kth largest and Kth smallest number in an array/ritesh.java b/Find the Kth largest and Kth smallest number in an array/ritesh.java new file mode 100644 index 0000000..4510da7 --- /dev/null +++ b/Find the Kth largest and Kth smallest number in an array/ritesh.java @@ -0,0 +1,24 @@ +import java.util.Arrays; + +public class KthLargestAndSmallest { + public static void main(String[] args) { + int[] arr = {12, 3, 1, 15, 9, 7}; + int k = 3; // Replace with your desired K value + + int kthLargest = findKthLargest(arr, k); + int kthSmallest = findKthSmallest(arr, k); + + System.out.println("Kth largest element: " + kthLargest); + System.out.println("Kth smallest element: " + kthSmallest); + } + + public static int findKthLargest(int[] arr, int k) { + Arrays.sort(arr); // Sort the array in ascending order + return arr[arr.length - k]; // Kth largest element is at index arr.length - k + } + + public static int findKthSmallest(int[] arr, int k) { + Arrays.sort(arr); // Sort the array in ascending order + return arr[k - 1]; // Kth smallest element is at index k - 1 + } +}