I'm trying to switch the biggest and smallest element in this array using a for loop, however I can't seem to figure out how to do it. Can someone help me? That would be very much appreciated, thanks!
public void assign(int[]IntArray) {
int BiggestNumber = IntArray[0];
int SmallestNumber = IntArray[0];
for(int i = 0; i < IntArray.length; i++) {
if(IntArray[i] > BiggestNumber) {
BiggestNumber = IntArray[i];
} else if(IntArray[i] < SmallestNumber) {
SmallestNumber = IntArray[i];
}
}
BiggestNumber = IntArray[SmallestNumber];
System.out.println(BiggestNumber);
}
There can be multiple solutions to this problem.
I'd work with the indices instead of the values/numbers, ie BiggestNumber and SmallestNumber being the indices of biggest and smallest number respectively. Then, I'd compare the value of IntArray[i] with IntArray[BiggestNumber] and IntArray[SmallestNumber] and if true, then store the index i
in BiggestNumber or SmallestNumber. Then in the end, after my for
loop, I'd swap the values in the array at both indices using another variable.
To point you into the direction:
int BiggestNumber = 0;
int SmallestNumber = 0;
if(IntArray[i] > IntArray[BiggestNumber])
{
BiggestNumber = i;
}
And to swap:
int a = IntArray[BiggestNumber];
IntArray[BiggestNumber] = IntArray[SmallestNumber];
IntArray[SmallestNumber] = a;
Hopefully you'll be able to fill in the missing parts I leave for you to fill in the assignment.
PS: I assume the method is for an instance/object level, ie non-static per your code, otherwise, I'd add keyword static
to it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.