Zenek Banan
Zenek Banan

Reputation: 11

Why won't this sorting work

Ok, so I wrote a method which should sort an ArrayList object. And it does... sort of. The object is an array of 20 random numbers, and after executing piece of code shown below I get the following result:

[-7, -7, -7, -7, -7, -7, -7, -7, -7, -7, 13, 13, 13, 13, 13, 13, 13, 27, 27, 27]

public static void sortArray (ArrayList<Integer> arrayToSort)
{
    int smallestNum;

    for (int j=0; j<arrayToSort.size(); j++)
    {
        smallestNum = arrayToSort.get(j);
        for (int i=j; i<arrayToSort.size(); i++)
        {
            if (arrayToSort.get(i)<=smallestNum)
            {
                smallestNum = arrayToSort.get(i);
            }
        }
        arrayToSort.set(j, smallestNum);
    }       
}

Upvotes: 0

Views: 51

Answers (2)

Midhun MP
Midhun MP

Reputation: 107121

You are replacing j'th index value with i'th index value. So it creates a duplicate entry and also you will loose the previous value contained in j'th index.

Probably you need something like:

public static void sortArray (ArrayList<Integer> arrayToSort)
{
    int smallestNum;
    int smallestIndex;

    for (int j=0; j<arrayToSort.size(); j++)
    {
        smallestNum   = arrayToSort.get(j);
        smallestIndex = j;
        for (int i=j; i<arrayToSort.size(); i++)
        {
            if (arrayToSort.get(i)<=smallestNum)
            {
                smallestNum   = arrayToSort.get(i);
                smallestIndex = i;
            }
        }
        arrayToSort.set(smallestIndex, arrayToSort.get(j));
        arrayToSort.set(j, smallestNum);
    }       
}

Upvotes: 0

Dtor
Dtor

Reputation: 609

When you execute this line:

arrayToSort.set(j, smallestNum);

You are blowing away whatever was already in position j and losing it completely, that's why you see -7 duplicated until you get to where -7 was in the original array. You want to swap the smallest number into the jth position and the number in the jth position with where you grabbed the smallest number instead.

What you really want is more like:

public static void sortArray (ArrayList<Integer> arrayToSort)
{
    int smallestNum;
    int smallestPos;

    for (int j=0; j<arrayToSort.size(); j++)
    {
        smallestNum = arrayToSort.get(j);
        smallestPos = j;
        for (int i=j; i<arrayToSort.size(); i++)
        {
            if (arrayToSort.get(i)<=smallestNum)
            {
                smallestNum = arrayToSort.get(i);
                smallestPos = i;
            }
        }
        arrayToSort.set(smallestPos, arrayToSort.get(j);
        arrayToSort.set(j, smallestNum);
    }       
}

Upvotes: 2

Related Questions