I have a structure consisting of two elements char *word
and int number
. When I want to sort them using bubble sort, I have to write exchange parts for both of them:
int i,j,tmp;
char * temp;
for(i=0; i<max;i++)
{
for(j=0;j<max-i;j++)
{
if(strcmp(array[j].word,array[j+1].word)>0)
{
temp=array[j].word;
array[j].word=array[j+1].word;
array[j+1].word=temp;
tmp=array[j].number;
array[j].number=array[j+1].number;
array[j+1].number=tmp;
}
}
}
EDIT My struct declaration
typedef struct{
char *word;
int number;
}
words;
words *array=NULL;
What if I had n elements in the array ? That would be very time consuming to exchange everything. Is there any way to omit this?
OF COURSE except for other sorting algorithms, which I don't want to use (like qsort
).
If your concern is with the performance in the swapping process, you should consider and array of pointers of type the struct you are using:
struct your_stuct *arr[MAX];
If you set correctly this array, the swap will change only the memory addresses rather than the struct contents and it could run faster:
Within your inner loop you should use:
struct your_struct *temp;
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
Is this what you mean in your question?