Untitled
unknown
c_cpp
2 years ago
1.8 kB
10
Indexable
// Sort appointments by datetime
void sortAppointments(Appointment appoints[], int size)
{
int i, j, swapped = 0, done = 0;
Appointment temp;
for (i = 0; i < size - 1 || done == 1; i++)
{
// we subtract 'i' because we don't need to check indexed we have already visited and swapped
for (j = 0; j < (size - i - 1); j++)
{
int toSwap; // keeps track of whether an element is higher than the one in the previous index
if (appoints[j].date.year != appoints[j + 1].date.year)
{
toSwap = appoints[j].date.year - appoints[j + 1].date.year;
}
else if (appoints[j].date.month != appoints[j + 1].date.month)
{
toSwap = appoints[j].date.month - appoints[j + 1].date.month;
}
else if (appoints[j].date.day - appoints[j + 1].date.day)
{
toSwap = appoints[j].date.day - appoints[j + 1].date.day;
}
else if (appoints[j].time.hour - appoints[j + 1].time.hour)
{
toSwap = appoints[j].time.hour - appoints[j + 1].time.hour;
}
else
{
toSwap = appoints[j].time.min - appoints[j + 1].time.min;
}
// this swaps two array elements
if (toSwap > 0)
{
temp = appoints[j];
appoints[j] = appoints[j + 1];
appoints[j + 1] = temp;
// this lets us know there was at least one swap in the iteration
swapped = 1;
}
}
if (!swapped)
{
// Algorithm is done if there was no swap for an entire pass
done = 1;
}
}
}
Editor is loading...