Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...