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).
1 Answer