This is a perfect job for an index sort.
In an index sort, the original data remains exactly in the same order as you received it. No data is moved.
This program keeps the integer in a parallel int array, with it's string in a char array with two dimensions.
Quite simple and perfect for when you don't want data, to be moved, but need to have it displayed or output
to a file, in sorted order.
Code:
/* IndxSort.c by Adak. A small example of sorting through an index
status: ok
*/
#include <stdio.h>
#define NumItems 4
#define StringLen 30
int main() {
int i, j, temp;
int Index[NumItems];
//make 2 arrays, (which work in parallel). One for strings, and one for the int
int Int[NumItems] = { 7, 2, 11, 6 };
//and a few lines from The Rhyme of the Ancient Mariner:
char Strings[NumItems][StringLen] = {
{ "Water, water, everywhere" },
{ "And all the boards did shrink" },
{ "Water, water, everywhere" },
{ "Nor any drop to drink" }
};
//initialize the index array
for(i = 0; i < NumItems; i++)
Index[i] = i;
//now do a simple sort, using the initialized index array and the Int array
for(i = 0; i < NumItems - 1; i++) {
for(j = i + 1; j < NumItems; j++) {
if(Int[Index[i]] > Int[Index[j]] ) {
temp = Index[i];
Index[i] = Index[j];
Index[j] = temp;
}
}
}
//Now to see the sorted data, we do it by using the Index array
printf("\n\n\n Int and String data, sorted by Int[]:\n\n");
for(i = 0; i < NumItems; i++)
printf("Int: %d String: %s \n", Int[Index[i]], Strings[Index[i]]);
printf("\n\n\n Original Int and String data:\n\n");
//to see the unsorted data
for(i = 0; i < NumItems; i++)
printf("Int: %d String: %s \n", Int[i], Strings[i]);
printf("\n\n\t\t\t press enter when ready");
i = getchar();
return 0;
}
BTW: you can do what you need, using your structs, as well. This is just another option.
I used a simple sorter, so every line of code could be shown easily. There's no reason the sorter couldn't be a Quicksort, mergesort, or comb-11 sort, however.