I read a file with cities and its population and I am trying to sort the cities alphabetically using an insertion sort. The issue is that it sorts all of the elements except the first one. The first value in the unsorted list remains in index [0] in the sorted list. This is the code:
int i, j;
String v;
for (i = 1; i < cities.size()-1; i++)
{
v = cities.get(i);
j = i;
while (cities.get(j-1).compareToIgnoreCase(v) > 0 && j >=2)
{
cities.set(j, cities.get(j-1));
j--;
}
cities.set(j, v);
}
Any idea what's wrong?
Thank you.
for (i = 1; i < cities.size()-1; i++)?? Java arrays are zero indexed...Any reason why you're not usingCollections.sort?