# Java – Manually Sorting an Array in Ascending Order

arraysjavasorting

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!

#### Best Solution

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;
}
``````