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 4
JAVA PROGRAM
import java.util.*;
public class MyArray
{
//called function which returns the k th position
public static int getKthMin(int k)
{
//array declaration
int arr[] = {4,6,9,10,3,11,1,2,5,7,8};
int i = 0 ,temp=0;
//runs the loop it sorts the array in ascending order
for ( i = 0; i < arr.length; i++)
{
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//retunrs the k position of array
return arr[k];
}
//main function
public static void main(String[] args)
{
//creating a object
MyArray obj = new MyArray();
// calling a function & passing the parameter 7
returned value is stored in res variable
int res = obj.getKthMin(3);
//printing the retuned value
System.out.println(res);
}
}
OUTPUT