Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

There can be multiple solutions to this problem.

I'd work with the indices instead of the values/numbers, i.e. 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.

P.S.: I assume the method is for an instance/object level, i.e. non-static per your code, otherwise, I'd add keyword static to it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...