[SOLVED] Swapping numbers in an array
Alright I have the program I am intended to write<i> basically</i> completely running correctly minus one little snag up I can't seem to wrap my mind around to fix.
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}
my trouble is in swapping the last element to where the max element was located in the array i can only seem to replace the last element with the actualy maximum leaving the maximum in two places on the array
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;
}
}
}
}