Untitled

 avatar
unknown
java
2 years ago
2.3 kB
5
Indexable
import java.util.*;

public class FindMin {
    public static void main(String[] args) {
        int size = 10; // size of the array
        int[] numbers = new int[size]; // create an array of integers
        
        System.out.println("Please enter the Kth Number to find the Kth Smallest Number");
        Scanner scanner = new Scanner(System.in);
        int k = scanner.nextInt();
        scanner.close();

        // create a new random number generator
        Random random = new Random();

        // fill the array with random numbers
        for (int i = 0; i < size; i++) {
            numbers[i] = random.nextInt(100) + 1; // generate a random integer between 1 and 100
        }
        // print out the array
        for (int i = 0; i < size; i++) {
            System.out.print(numbers[i] + " ");
        }
        //Space Print
        System.out.println();

        for(int i= 0;i<k;i++)
        {
            // find the minimum value in the array
            int min = findMin(numbers, 0, Integer.MAX_VALUE);

            // print out the minimum value
            if(i == k-1)
            {
                System.out.println("The " + k + "th value is: " + min);
            }
            numbers = removeElement(numbers, min);
        }
    
    }

    public static int findMin(int[] arr, int index, int min) {
        if (index == arr.length) { // base case
            return min;
        }

        if (arr[index] < min) {
            min = arr[index];
        }

        return findMin(arr, index+1, min); // recursive call
    }

    public static int[] removeElement(int[] arr, int value) {
        int index = -1;
        // find the index of the element with the value to remove
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == value) {
                index = i;
                break;
            }
        }
        // if the element is not found, return the original array
        if (index == -1) {
            return arr;
        }
        int[] newArr = new int[arr.length - 1];
        // copy all the elements from the original array to the new array except the one to remove
        for (int i = 0, k = 0; i < arr.length; i++) {
            if (i == index) {
                continue;
            }
            newArr[k++] = arr[i];
        }
        return newArr;
}
}
Editor is loading...