I currently have an array containing objects called 'People'. Each one has a name, day, month, year (of birth). I want to convert these to dates and use the .isAfter() method to compare them and resort them but it does not sort them by date at all. Here is a simpler version of the code
for (int i = 0; i<peopleArray.size()-1; i++)
{
for (int j = 0; j<peopleArray.size()-1; j++)
{
LocalDate firstDate = LocalDate.of(Integer.parseInt(peopleArray.get(i).getDOBYear()),
Integer.parseInt(peopleArray.get(i).getDOBMonth()),
Integer.parseInt(peopleArray.get(i).getDOBDay()));
LocalDate secondDate= LocalDate.of(Integer.parseInt(peopleArray.get(j).getDOBYear()),
Integer.parseInt(peopleArray.get(j).getDOBMonth()),
Integer.parseInt(peopleArray.get(j).getDOBDay()));
if(firstDate.isAfter(secondDate))
{
Person temp = peopleArray[i];
peopleArray[i] = peopleArray[i+1];
peopleArray[i+1] = temp;
}
}
}
'Person' is the name of the object. Thanks a lot for your help in advance!
If your looking for a simpler solution in java, then solution by user2004685
should do.
Since you've tagged bubble-sort
, I'm guessing you need help with the issue in your code.
Issues:
i/j < size()
.i
and j
location but swapping i
and i+1
Code with Correction:
for (int i = 0; i<peopleArray.size(); i++)
{
for (int j = 0; j<peopleArray.size(); j++)
{
LocalDate firstDate = LocalDate.of(Integer.parseInt(peopleArray.get(i).getDOBYear()),
Integer.parseInt(peopleArray.get(i).getDOBMonth()),
Integer.parseInt(peopleArray.get(i).getDOBDay()));
LocalDate secondDate= LocalDate.of(Integer.parseInt(peopleArray.get(j).getDOBYear()),
Integer.parseInt(peopleArray.get(j).getDOBMonth()),
Integer.parseInt(peopleArray.get(j).getDOBDay()));
if(firstDate.isAfter(secondDate))
{
Person temp = peopleArray[i];
peopleArray[i] = peopleArray[j];
peopleArray[j] = temp;
}
}
}