Computer Science, asked by itengineering2001, 4 months ago

write java program to find kth largest and smallest element in an array?

Answers

Answered by ItsBrainest
2

import java.util.*;

public class Solution {

public static void main(String[] args)

{

Integer arr[] = new Integer[]{1, 4, 17, 7, 25, 3, 100};

int k = 2;

System.out.println("Original Array: ");

System.out.println(Arrays.toString(arr));

System.out.println("K'th smallest element of the said array: ");

Arrays.sort(arr);

System.out.print(arr[k-1] + " ");

System.out.println("\nK'th largest element of the said array:");

Arrays.sort(arr, Collections.reverseOrder());

System.out.print(arr[k-1] + " ");

}

}

Answered by samarthkrv
1

Answer:

import java.util.Scanner;

public class Main

{

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.print("Enter the number of elements in the array:");

    int n = sc.nextInt();

    int[] arr = new int[n];

    System.out.println("Enter all " + n + " elements in the array:");

        for(int i = 0; i < n; i++){

            arr[i] = sc.nextInt();

        }

    System.out.println("---THE ORIGINAL ARRAY---");

        for(int i = 0; i < n; i++){

            System.out.print(arr[i] + " ");

        }

    int max = arr[0], min = arr[0];

        for(int i = 0; i < n; i++){

            if(arr[i] > max){

                max = arr[i];

            }

            if(arr[i] < min){

                min = arr[i];

            }

        }

   System.out.println("\nThe largest number in the array is " + max);

   System.out.println("The smallest number in the array is " + min);

}

}

Explanation:

Similar questions