In: Computer Science
Program in Java Create a class and name it MyArray and implement following method. * NOTE: if you need more methods, including insert(), display(), etc. you can also implement those. Method name: getKthMin(int k) This method receives an integer k and returns k-th minimum value stored in the array. * NOTE: Items in the array are not sorted. If you need to sort them, you can implement any desired sorting algorithm (Do not use Java's default sorting methods). Example: Items in the array: 4, 6, 9, 10, 3, 11, 1, 2, 5, 7, 8 call the method to get 3rd min value myArray.getKthMin(3); -> this will return 3
Answer: For this Code in java I have given the option to choose the number of element You want to be in the array and then sort the array and accordingly return the element at that position of the sorted array.
Here is the Code:
import java.util.Scanner;
public class MyArray
{
public static void main(String[] args)
{
int n,num;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
n=sc.nextInt();
System.out.print("Enter the position of element you want to find: ");
num=sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<n; i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Array elements after sorting:");
//sorting logic
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
int tmp = 0;
if (arr[i] > arr[j])
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
System.out.print(arr[i]+" ");
}
System.out.println("The Element is: "+arr[num-1]);
}
}
Now take the Glimse of the code run:
Have a Happy Coding!!