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

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

How do I switch these 2 elements in this JAVA array?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...