Bluasul - 5 months ago 41

Java Question

I'm trying to use this method to sort an integer array in ascending order. But my for loop runs through it only once.

`public void sortArray()`

{

boolean sorted = false;

while(sorted == false)

{

int temp;

for(int i = 0; i < inArray.length - 1; i++)

{

if(inArray[i] > inArray[i + 1])

{

temp = inArray[i];

inArray[i] = inArray[i + 1];

anArray[i + 1] = temp;

}

}

sorted = true;

}

}

I know it has to do with how I'm handling that boolean flag, but I'm not sure how to go about fixing it. Any suggestions would be appreciated. Thanks in advance.

Answer

There are multiple issues here:

`while (sorted = false)`

sets`sorted`

to`false`

and then tests the resulting value`false`

, meaning that you never enter the loop body*at all*(not once as per your question).If you fix that, your code will only run the

`while`

loop body**once**(thus leaving the array not sorted yet), because you have`sorted = true`

as an*unconditional*statement at the end of the loop body.

You need to have a flag that assumes the array is sorted, and then is cleared if you find evidence it wasn't, something like:

```
public void sortArray()
{
boolean sorted;
do
{
sorted = true; // Assume it's sorted
int temp;
for(int i = 0; i < inArray.length - 1; i++)
{
if(inArray[i] > inArray[i + 1])
{
temp = inArray[i];
inArray[i] = inArray[i + 1];
anArray[i + 1] = temp;
sorted = false; // We changed something, so assume we need to do another pass
}
}
}
while (!sorted);
}
```

Side note: This is just a style thing, but it's generally best to scope variables as narrowly as possible. There's no need for `temp`

to be outside the `for`

loop or even outside the `if`

block, move it *inside* the `if`

block

```
public void sortArray()
{
boolean sorted;
do
{
sorted = true; // Assume it's sorted
for(int i = 0; i < inArray.length - 1; i++)
{
if(inArray[i] > inArray[i + 1])
{
int temp = inArray[i];
inArray[i] = inArray[i + 1];
anArray[i + 1] = temp;
sorted = false; // We changed something, so assume we need to do another pass
}
}
}
while (!sorted);
}
```