# Thread: Insertion Sort on Array of Structs

1. ## Insertion Sort on Array of Structs

I'm trying to take my working selection sort (values largest to smallest ) and switch it a with an Insertion sort (values smallest to biggest). I have the year comparison working the problem is I'm exactly sure how I would compare the day and month using the insertion sort
Code:
```Here is my Selection Sort
int selectionSort(struct date *array, int size)
{
int i, j,temp;
int moves =0;

for(i=0; i<(size-1); i++)
for(j=i+1; j<size; j++){
if (array[i].year < array[j].year){
swap(array, i, j);
moves++;
}
else if(array[i].year == array[j].year)
if(array[i].month<array[j].month){
swap(array, i, j);
moves++;
}
else if(array[i].year == array[j].year)
if(array[i].month == array[j].month)
if(array[i].day < array[j].day){
swap(array, i, j);
moves++;
}

}

return moves;
}

Here is what I have for my Insertion Sort

void insertSort(struct date *array, int size)
{
int i, j, current;

for(i=1; i<size; i++)
{
current = array[i].year;
j = i;
while((j > 0) && (array[j-1].year > current))
{
array[j].year = array[j-1].year;
j = j - 1;
}
array[j].year = current;
}
}```

2. If it was me, I would probably write a separate function to compare dates. You might need it in other situations as well.

3. coulld there be any other way

4. There is ALWAYS another way, but writing a function that compares a date to another date and returns (for example) -1, 0 or 1 depending on whether first date is less, equal or greater than the second date.

That would make your selection sort much simpler too:
Code:
```int selectionSort(struct date *array, int size)
{
int i, j,temp;
int moves =0;

for(i=0; i<(size-1); i++) {
for(j=i+1; j<size; j++){
if (cmpDate(array[i], array[j]) > 0){
swap(array, i, j);
moves++;
}
}
}
return moves;
}```
I also added the outer (red) braces to make it more readable and maintainable.

--
Mats