Boxiom
Boxiom

Reputation: 2305

Swapping array values with minimum value

So what I'm trying to do is to sort an array by going through the whole array and each time swap the value with the minimum value in the array. I've created a method to find minValue, but I'm not sure how to swap that value with my current value. This is probably a horrible explanation, but here's the code:

public static int findMin(int[] numList, int start, int end){

    int minIndex = numList[0];
    for (int i = start; i < end; i++) {
        if(numList[i] < minIndex){
            minIndex = numList[i];
        }
    }

    return minIndex;
}

And my loop which is supposed to sort the array:

for (int i = 0; i < numList.length; i++) {
        int minIndex = findMin(numList,i,10);
        numList[i] = minIndex;
    }

So as you can see, this only replaces numList[i] with the minValue. So how can I swap the value already in numList[i] with wherever in the array minValue was found?

Thanks!

Upvotes: 0

Views: 1488

Answers (3)

gispyDangre
gispyDangre

Reputation: 91

The Corrected method is

public static int findMin(int[] numList, int start, int end){

        int minVal= numList[start];
        int minIndex = start;
        for (int i=start; i <end; i++) {
            if(numList[i] <minVal){
               minIndex=i;
               minVal=numList[i];
            }
        }

        return minIndex;
    }

And the corrected loop is

for (int i = 0; i < numList.length; i++) {
            minIndex = findMin(numList,i,numList.length);
            temp=numList[i];
            numList[i]=numList[minIndex];
            numList[minIndex]=temp;
        }

Upvotes: 1

nanofarad
nanofarad

Reputation: 41271

You need to copy the value to a temporary integer to swap:

int temp = numList[i];
numList[i] = numList[minIndex];
numList[minIndex] = temp;

Upvotes: 2

jester
jester

Reputation: 3489

You have to use a temporary integer

int temp = numList[i];
numList[i] = numList[minIndex];
numList[minIndex] = temp;

In your findMin() I think

int minIndex = numList[0];

should be

int minIndex = numList[start];

because after the first swap, numlist[0] will be the smallest value. The minimum value should be searched for in the rest of the array, so that we get successively larger values in each iteration.

Upvotes: 1

Related Questions