Can someone explain how this method works? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Can someone explain how this method works? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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).

We are here to answer your question about Can someone explain how this method works? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji