# Thread: Insertion sort - sort an array of structs using a single field

1. ## Insertion sort - sort an array of structs using a single field

I have an array of structs
Code:
```typedef struct node
{
int a,b,c,d;
} element;

...

element array;```
i want to compare the field a
Code:
`if (niz[j].a > niz[j+1].a)`
but swap the entire element.

basiccaly doing what excel does, when you sort one column which is asociated with other columns.

i.e.

Code:
```PRE SORT
=========

20	14	32
13	21	26
19	17	11

POST SORT
=========

13	21	26
19	17	11
20	14	32```
the problem is, i don't know how to do it with insertion sort. this is my insertion sort which works on a "normal" 1D int array but I need to modify it

Code:
```void Insertion (int array[], int n)
{
int i;

for (i=0; i < n; i++)
{
int j, temp = array[i];

for (j = i - 1; j >= 0; j--)
{
if (array[j] <= v) break;
array[j + 1] = array[j];
}

array[j + 1] = temp;

}

}``` 2. solved it. trivial really but not a couple of hours ago one simply needs to keep track of the element from which we are using the desired field for comparison. I called it element x Code:
```int i;
element x;

for (i=0; i < n; i++)
{
int j, v = array[i].a;
x = array[i];

for (j = i - 1; j >= 0; j--)
{
if (array[j].a >= v) break;
array[j + 1] = array[j];

}

array[j + 1].a = v;
array[j + 1] = x;
}``` Popular pages Recent additions insertion, sort, struct 