Can someone explain how this method works?

The method is about to delete a city for the smallest population!

The method:

public void delCity(long population) {
    if (population== 0) {
        System.out.println("There is no city!");
        return;
    }

    for (int i = 0; i < index; i++) {
        if (cities[i].getPopulation() < population) {
            for (int j = i; j < index - 1; j++) {
                cities[j] = cities[j + 1];
            }
            cities[--index] = null;
            i--;
        }
    }
}

So the part i don’t understand is the body of the second for-loop, for example how cities[j] = cities[j + 1]; works and what does the cities[--index] = null; i--;? I would really appreciate your responses.

Answer

This loop is shifting all the values of the array [from the position i, that is the city to delete]. (Because the array is static, otherwise there is null between elements )

for (int j = i; j < index - 1; j++) {
    cities[j] = cities[j + 1];
}

Then is setting last element to null and decreasing index;

 cities[--index] = null;

Here an explaination of the shifting: enter image description here enter image description here

As mentioned into comments. Your complexity is O(N²). But just changing your data structure (for example, using Lists), you can improve it to O(N).

Leave a Reply

Your email address will not be published. Required fields are marked *