Code:
#include <stdio.h>
#include <string.h>
#define SIZE 20
void sort(char a[][SIZE], int *, int);
void swap(char a[][SIZE], int *, int, int);
int main(void) {
int i,n,b[4]={40,30,50,70};
char a[4][20]={{"Adam"},{"Abigail"},{"Abby"},{"Abe"}};
n=SIZE;
printf("\nBefore sorting\n a: b:\n\n");
for(i=0;i<n;i++)
printf("%s %3d\n",a[i],b[i]);
sort(a,b,n,0); //sort with a as the key
printf("\nAfter sorting, A is the key:\n a: b:\n\n");
for(i=0;i<n;i++)
printf("%s %3d\n",a[i],b[i]);
//now sort it with b[] as the key
sort(a,b,n,1);
for(i=0;i<n;i++) {
printf("%s %3d\n",a[i],b[i]);
}
printf("\n");
return 0;
}
//a substitution sort
void sort(char a[][SIZE], int *b, int n, int type) {
int i,j;
if(!type) {
for(i = 0;i < n-1; i++) {
for(j = i+1;j<n;j++) {
if(strcmp(a[i],a[j])>0) {
swap(a,b,i,j);
}
}
}
}
else {
for(i=0;i<n-1;i++) {
for(j=i+1;j<n;j++) {
if(b[i] > b[j]) {
swap(a,b,i,j);
}
}
}
}
}
//swaps both arrays, so the data stays with the right name
void swap(char a[][3], int *b, int i, int j) {
int temp;
char ctemp[SIZE];
strcpy(ctemp,a[i]);
strcpy(a[i], a[j]);
strcpy(a[j], ctemp);
//swap the b array
temp = b[i];
b[i] = b[j];
b[j]= temp;
}
Parallel arrays are taught before structs, but structs are far more versatile to work with. With only two items, either parallel arrays or structs, are good. If you had 3 or more data entries per record, structs would definitely be what you'd want to use.