In an array with null spaces, how can consolidate all of the non null values together?

994 Views Asked by At

Hey so I have this homework assignment and I'm having issues with one of the methods. I would like hints and not actual answers/code.

So I have a class called HorseBarn that messes with an array of horses(horse being the type). My problem is I'm having troubles with the consolidate method.

What the array would look like before consolidate: a,b,c,d are horses

|a|null|b|null|c|d|

What the array would look like after consolidate:

|a|b|c|d|null|null|

So my logic would be to make a nested for loop. The first loop would search for a null value, once the first loop finds the null value, the second loop would look for a horse and then swap with it. Then the second loop would end and go back to the first loop. So here is what I have right now and it doesn't work(it just terminates). Is my logic wrong or is it my syntax that's causing the problems?

public void consolidate()
{
    int j = 0;
    for(int i = 0; i < spaces.length;i++)
    {
        if( spaces[i] == null)
        {
            for(j = i; j < spaces.length && spaces[j] == null; j++)
            {

            }
            spaces[i] = spaces[j];
            spaces[j] = null;
        }

    }
2

There are 2 best solutions below

5
On BEST ANSWER

Well for starters, this should give an index out of bounds exception if the last non-null is found and there still are elements remaining:

ex: horses = | a | null | null | null |

for i = 1, since horses[1] -> horses[3] are empty, j first gets set to 1 then ends with j = 4 (because of the termination condition j < horses.length())

You would then try to swap horses[1] with horses[4], which throws the array index out of bounds

0
On

In the inner for loop, just find the position of next non null value and break it there. Then swap it with your null. A better time efficient code.