class Main { public static void main (String[] args) { int[] arr = {16, 5, 5, 4, 13, 2, 0}; System.out.println(findMin(arr, 3, 6)); } public static int findMin (int[] arr, int minIndex, int maxIndex) { int min = arr[minIndex]; // set the min value at arr[3] for (int i = minIndex; i < maxIndex; i++) // start at arr[3] { // and go to arr[5] if (arr[i] < min) // if arr[3] < arr[3] then min = arr[3] { min = arr[i]; } // if arr[4] < arr[3] then min = arr[4] } return min; // return arr[4] } }
I created a method that accepts an integer array as a parameter and returns the element with the smallest value as the return value; in essence, all that was required was a loop that iterated until the view became empty. Then, I changed my method to include two additional parameters: the method is supposed to find the minimum value in the array within the given index range instead of the entire array since int startIndex and endIndex are supposed to limit the view on the array. The function findMin(arr, 2, 5) checks indices 2, 3, 4, and 5 and returns 2 as the smallest number in the array's range. I also found a method to swap two array indices, such as swap(array, 3, 7) to replace index 3 with index 7.
public static void swap (int[] arr, int index1, int index2) { int temp = arr[index1]; arr[index1] = arr[index2]; arr[index2] = temp; }
Right now, I'm stuck on*modifying*the findMin method so that it returns the index of the min element rather than the actual min element. And maybe rename it to findMinIndex.
Can someone help me?