1

Two versions of very similar code... one works, the other doesn't...

Array Used:

int[] input = new int[10];  

//

for(int i = 0; i < input.length; i++) {
                //int inputi = input[i];
            for(int j = 0; j < input.length; j++) {
                //int inputj = input[j];
                if(input[i] < input[j]) {
                      input[j] = input[i];
                      min = input[j];
                  }
            }

The code above works. The code below doesn't, what gives?

for(int i = 0; i < input.length; i++) {
                int inputi = input[i];
            for(int j = 0; j < input.length; j++) {
                int inputj = input[j];
                if(inputi < inputj) {
                      inputj = inputi;
                      min = inputj;
                  }
            }

Shouldn't it do the exact same thing? The first code returns the minimum value, the second does not.

Sorry for the possibly confusing variable names, I only chose those so I could easily switch back and forth.

2 Answers 2

3

the assignment is broken: inputj and inputi are temporary variables.

                  inputj = inputi;

changes temporary variable

                  input[j] = input[i];

actually changes the array values.

just to get the min value:

min = input[0];
for(int i = 1; i < input.length; i++) {
            if(min > input[i]) {
                  min = input[i];
            }
}
Sign up to request clarification or add additional context in comments.

6 Comments

How can I grab the right value without reassigning the array value?
if you just want the minimum value, you can do a single pass
@Foo Bah: Do you think you could explain what that means? I'm sorry, I'm still learning so much.
if you want te sorted array, you either need to copy the array [external sorting] or manipulate the array
if you only want to find the minimum value, the code in my response will compute the minimum. If you want to actually sort the result, your first code block is almost correct (instead of just assigning, you should swap input[i] and input[j])
|
1

Are you just trying to get the minimum value of the array?

int min = input[0];
for (int i = 0; i < input.length; i++) {
  if (input[i] < min) {
    min = input[i];
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.