-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkth smallest and largest element in an array.
More file actions
61 lines (55 loc) · 1.2 KB
/
kth smallest and largest element in an array.
File metadata and controls
61 lines (55 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//WAP to find kth smallest and largest element in an array.
import java.util.*;
public class Test {
static int arr[]=new int[20];
static int n;
static int max(){
int max=arr[0];
for(int i=1; i<n; i++){
if(arr[i]>max)
max=arr[i];
}
return max;
}
static int min(){
int min=arr[0];
for(int i=1; i<n; i++){
if(arr[i]<min)
min=arr[i];
}
return min;
}
static void delete(int value){
for(int i=0; i<n; i++){
if(arr[i]==value){
for(int j=i; j<n-1; j++){
arr[j]=arr[j+1];
}
n--;
}
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int m=sc.nextInt();
n=m;
int a[]=new int[m];
System.out.print("Enter the elements in the array: ");
for(int i=0; i<m; i++)
a[i]=sc.nextInt();
arr=a;
System.out.print("Enter the value of k for kth smallest and largest element : ");
int k=sc.nextInt(),max=0, min=0;
for(int i=1; i<=k; i++){
max=max();
if(i<k)
delete(max);
min=min();
if(i<k)
delete(min);
}
System.out.println("The kth smallest element is "+min);
System.out.println("The kth largest element is "+max);
}
}