'Trying to swap min and max values in an array java
import java.util.Arrays;
public class Swap
{
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
System.out.print("What is the size of your array? ");
int myArray = console.nextInt();
int[] size = new int[myArray];
int sum = 0;
int max = 0;
int min = 100;
int temp = 0;
for (int i = 0; i < size.length; i++)
{
System.out.print("Array index " + (i) + ": ");
size[i] = console.nextInt();
sum += size[i];
if (size[i] > max) max = size [i];
if (size[i] < min) min = size [i];
}
System.out.println ("\nmaximum value is: " + max);
System.out.println ("\nminimum value is: " + min);
System.out.println (Arrays.toString(size));
temp = size[max];
size[max] = size[min];
size[min] = temp;
System.out.println (Arrays.toString(size));
}
}
I am having trouble swapping the min and max value in the array, I am able to find those values fine, and I even found a way to swap in with the temp variable, but I can't translate that into the array.
Solution 1:[1]
Only the part for max and min.
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int iAtMax = -1;
int iAtMin = -1;
for (int i = 0; i < size.length; i++) {
if (iAtMax == -1 || max < size[i]) {
iAtMax = i;
max = size[i];
}
if (min <= size[i]) {
iAtMin = i;
min = size[i];
}
}
if (iAtMax != -1) {
int temp = size[iAtMax];
size[iAtMax] = size[iAtMin];
size[iAtMin] = temp;
}
You could initialize max and min so that an update in the loop always updates. Then you have to use <= max resp. >= min to update the indices. (See min above) or you can check whether there already is a max and min.
If the array is empty (or size 1) you cannot (resp. need not) swap.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joop Eggen |
