Alright I have the program I am intended to write basically completely running correctly minus one little snag up I can't seem to wrap my mind around to fix.
The programs intention is to search through an array based upon the parameters you input and find the maximum number.
Then replace the last parameter of the array with the maximum and the place in the array where the maximum was with the last parameters number.
What I can't seem to figure out is how to replace the maximums location with the last number in the selected area of the array i can only manage to replace the last number with the actual maximum
heres the actual question and the code i've worked up
The programs intention is to search through an array based upon the parameters you input and find the maximum number.
Then replace the last parameter of the array with the maximum and the place in the array where the maximum was with the last parameters number.
What I can't seem to figure out is how to replace the maximums location with the last number in the selected area of the array i can only manage to replace the last number with the actual maximum
heres the actual question and the code i've worked up
Code:
Consider a integer array called myArray of size 20 that
initially contains random numbers between 1 and 1000. You want to write a method,
blockMax that accepts myArray and two integers, start and end as parameters.
blockMax considers the sub-array of myArray denoted by start and end, and finds the
maximum element in that sub-array. Subsequently, blockMax swaps the max element
and the last element of the sub-array. For example, if initially
myArray is {95, 90, 104, 85, 90, 110, 105, 88, 90, 97, 102, 77, 100, 90, 109,
80, 34, 9, 567, 876}
and we make the call
blockMax(myArray, 4, 10)
then the result reflected in myArray will be
{95, 90, 104, 85, 90, 102, 105, 88, 90, 97, 110, 77, 100, 90, 109, 80, 34, 9,
567, 876}
Code:
import javax.swing.JOptionPane;
public class MaxVal{
public static void main(String[] args) {
int[] myArray = new int[20];
String startStr, endStr;
int start, end;
startStr = JOptionPane.showInputDialog("Input start..(0-19)");
start = Integer.parseInt(startStr);
endStr = JOptionPane.showInputDialog("Input end..(start-19)");
end = Integer.parseInt(endStr);
for (int i = 0; i < myArray.length; i++){
myArray[i] = (int)(Math.random() * 1000);
}
System.out.println("myArray is: ");
printArray(myArray);
System.out.println("The Array after blockMax: ");
blockMax(myArray, start, end);
printArray(myArray);
}
static void printArray (int[] array) {
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println();
}
static void blockMax(int[] array, int inputStart, int inputEnd) {
int max = array[inputStart];
for (int i = inputStart; i < inputEnd; i++){
if (max < array[i]){
max = array[i];
int temp = array[inputEnd];
array[inputEnd] = max;
}
}
}
}