C H.W
typedef struct { int sid; int tel; } STUDENTX; STUDENTX sx[5]; // This looks like below
sx[0] sx[1] sx[2] sx[3] sx[4]
sid sid sid sid sid
tel tel tel tel tel
sx[0].sid = 44; sx[0].sid = 12;
sx[1].sid = 14; sx[1].sid = 32;
sx[2].sid = 24; sx[2].sid = 11;
sx[3].sid = 54; sx[3].sid = 14; // after these assignments, sx[] looks like below
sx[0] sx[1] sx[2] sx[3] sx[4]
44 14 24 54 sid
12 32 11 14 tel
STUDENTX *ptr[5];
ptr[0] = &sx[0];
ptr[1] = &sx[1];
ptr[2] = &sx[2];
ptr[3] = &sx[3];
ptr[4] = &sx[4]; //after these pointer assignments, ptr[] looks like below
ptr[0] ptr[1] ptr[2] ptr[3] ptr[4]
&sx[0] &sx[1] &sx[2] &sx[3] &sx[4]
sx[0] sx[1] sx[2] sx[3] sx[4]
44 14 24 54 sid
12 32 11 14 tel
STUDENTX *t;
t = ptr[1]; // t = &sx[1]
ptr[1] = ptr[2]; // ptr[1] = &sx[2]
ptr[2] = t; // ptr[2] = &sx[1]
ptr[0] ptr[1] ptr[2] ptr[3] ptr[4]
&sx[0] &sx[2] &sx[1] &sx[3] &sx[4]
sx[0] sx[1] sx[2] sx[3] sx[4]
44 14 24 54 sid
12 32 11 14 tel
Bubble sort using the pointers.
sorted = 0; // this is to go into the while loop.
while( sorted == 0) // while not sorted, we do below
{
sorted = 1; // let's assume it is sorted
for(i=0; i<NUM-1; i++) // i gose 0 to NUM-2, and (i+1) goes 1 to NUM-1
{ STUDENTX *t; // t will contain address of data of STUDENT type
if( ptr[i]->sid > ptr[i+1]->sid ) // compare sid,
{ t = ptr[i];
ptr[i] = ptr[i+1];
ptr[i+1] = t;
sorted = 0; // ahhhh, not sorted yet
}
}
// at this point, if sorted is still 1, every pair was in order, thus sorted.
}