0
public static int[] sortArr(int[] a){
    int temp;
    for(int i = 0; i < a.length; i++){
        temp = a[i];
        a[i] = a[findMin(a, i)];
        a[findMin(a, i)] = temp;
    }
    return a;
}
public static int findMin(int[] a, int start){
    int min = a[start];
    int minIndex= start;
    for(int i = start; i < a.length; i++){
        if(a[i] < min){
            min = a[i];
            minIndex = i;
        }
    }
    return minIndex;
}

the sortArr method just returns the array that it is given, and I can't see why. I've worked it out on paper and it should be working. Can anybody see the problem?

2
  • Which variable do you return in findMin(), min or minIndex? Commented Mar 21, 2016 at 21:30
  • I just edited it, i return minIndex to find the location of the smallest value Commented Mar 21, 2016 at 21:35

1 Answer 1

6

You're calling findMin twice, but the code on the same line as the first call is causing the result of the second call to change.

You have:

a[i] = a[findMin(a, i)]; // findMin() returns the min, and you'll move that to a[i]
a[findMin(a, i)] = temp; // findMin() returns the new min == i

Instead use:

int min = findMin(a, i);
a[i] = a[min];
a[min] = temp;
Sign up to request clarification or add additional context in comments.

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.