Problem:
Given a randomly ordered array of n elements determine the kth smallest element in the set.
Solution:
package array.programs;
import java.util.Arrays;
import java.util.Scanner;
public class KthSmalletElement {
int[] numbers;
int k;
public static void main(String[] args) {
KthSmalletElement kthSmalletElement = new KthSmalletElement();
kthSmalletElement.getTheNumbers();
kthSmalletElement.findKthSmallestElement();
}
public void getTheNumbers(){
Scanner scanner = new Scanner(System.in);
System.out.println("how many numbers");
numbers = new int[scanner.nextInt()];
for (int i = 0; i < numbers.length; i++) {
System.out.println("enter number");
numbers[i] = scanner.nextInt();
}
System.out.println("enter which smallest element you want to find");
k = scanner.nextInt();
scanner.close();
}
public void findKthSmallestElement(){
Arrays.sort(numbers);
System.out.println("the array is ");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
System.out.println("the smallest element is " + numbers[k - 1]);
}
}
Output:
how many numbers
5
enter number
123
enter number
33
enter number
444
enter number
2
enter number
33333
enter which smallest element you want to find
3
the array is
2 33 123 444 33333
the smallest element is 123
Given a randomly ordered array of n elements determine the kth smallest element in the set.
Solution:
package array.programs;
import java.util.Arrays;
import java.util.Scanner;
public class KthSmalletElement {
int[] numbers;
int k;
public static void main(String[] args) {
KthSmalletElement kthSmalletElement = new KthSmalletElement();
kthSmalletElement.getTheNumbers();
kthSmalletElement.findKthSmallestElement();
}
public void getTheNumbers(){
Scanner scanner = new Scanner(System.in);
System.out.println("how many numbers");
numbers = new int[scanner.nextInt()];
for (int i = 0; i < numbers.length; i++) {
System.out.println("enter number");
numbers[i] = scanner.nextInt();
}
System.out.println("enter which smallest element you want to find");
k = scanner.nextInt();
scanner.close();
}
public void findKthSmallestElement(){
Arrays.sort(numbers);
System.out.println("the array is ");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println();
System.out.println("the smallest element is " + numbers[k - 1]);
}
}
Output:
how many numbers
5
enter number
123
enter number
33
enter number
444
enter number
2
enter number
33333
enter which smallest element you want to find
3
the array is
2 33 123 444 33333
the smallest element is 123
No comments:
Post a Comment