Exercise #1
unknown
java
3 years ago
3.2 kB
5
Indexable
import java.util.*;
public class FindMin
{
public static void main(String[] args)
{
// Prompt user for array size
System.out.println("Please enter how long you want the array to be:");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt(); // Size of the array
int[] numbers = new int[size]; // Create an array of integers
// Prompt user for the value of K
System.out.println("Please enter the Kth Number to find the Kth Smallest Number:");
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] + " ");
}
// Print a new line
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 Kth minimum value
if (i == k - 1)
{
if (k == 2)
{
System.out.println("The " + k + "nd smallest value is: " + min);
}
else if (k == 3)
{
System.out.println("The " + k + "rd smallest value is: " + min);
}
else
{
System.out.println("The " + k + "th smallest value is: " + min);
}
}
numbers = removeElement(numbers, min);
}
}
/**
* Recursive function to find the minimum value in the array.
*/
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
}
/**
* Function to remove the given value from the array and return a new array without the removed value.
*/
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...