Swapping two constructors using pointers
I have been studying from Foundation of Computer Science by Jeffrey Ullman and came upon an exercise (on page 32; "Sorting Keys").
Suppose we have a constructor STUDENT as following:
struct STUDENT{ int StudentID; char *name;
char grade; } A[MAX];
and we wish to swap two STUDENT constructors on the basis of the condition:
A[j].StudentID < A[small].StudentID;
where 'small' is the smallest known StudentID value till a particular iteration of a loop.
Now, one way to this would be to swap every variable of the strucute with each other. Like this:
TempA.StudentID = A[j].StudentID;
A[j].StudentID = A[small].StudentID;
A[small].StudentID = TempA.StudentID;
and so on for every variable in the strusture.
This will take loads of time which only increase as the number of variable in the strucutre increase.
So, the book highlights a solution to this:
"Since it is time-consuming to swap whole structures, a more efficient approach
is to use a second array of pointers to STUDENT structures and sort only the pointers
in the second array. The structures themselves remain stationary in the first array.
We leave this version of selection sort as an exercise."
Here is an idea about how to do it..
STUDENT *St[MAX]; for(int j=0; j<MAX; j++) { St[j] = &A[j]; } if(A[i].Sal < A[0].Sal) swap(St[i],St[0]);
Where swap function is defined as: void swap(STUDENT **A, STUDENT **B) { STUDENT temp = *A; *A = *B; *B = temp; }