Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually Sorting an Array in Ascending Order

I have a homework assignment to sort an array in ascending order. Obviously, this is to be done manually without using any kind of sort() function.

I figured to do it, I would need two for loops: the first one will loop through the existing array and create a temporary value with the value and index of the array. The second loop will compare the temporary values to the existing values and sort them. I keep trying to write the code, but I just can’t seem to get it right. Here is the latest method I came up with:

public int[] sortArray (int[] inArray)
{
    //Construct the array we're using here
    int[] newArray = inArray;

    for(int x = 0; x < a.length; x++) //a.length = # of indices in the array
    {
        int tempValue = a[x];
        int tempIndex = x;

        for(int y = 0; y < a.length; y++)
        {
            if(tempValue < a[y])
            {
                newArray[x] = tempValue;
            }
        }
    }

    return newArray;
}

I’m pretty sure this is incorrect, but if someone could push me in the right direction it would be very appreciated!

like image 482
Andrew De Forest Avatar asked Mar 29 '12 14:03

Andrew De Forest


1 Answers

You have a nearly OK version of the Selection Sorter. You need to start your y at x+1, not at 0. Otherwise you're re-scanning the sorted portion of the array. You should also note that selection sort is an in-place algorithm; if you are looking to make a copy of the array, you should use Arrays.copy method, otherwise int[] newArray = inArray; is creating an alias, not a copy. Finally, the if statement in the nested loop should swap a[x] and a[y], not simply put tempValue in:

if(newArray[x] < newArray [y]) {
    int tempValue = newArray[y];
    newArray[y] = newArray[x];
    newArray[x] = tempValue;
}
like image 79
Sergey Kalinichenko Avatar answered Oct 06 '22 01:10

Sergey Kalinichenko