I am working on a coding problem where I have to sort an array of words(pointers to strings) by the length of the word. I have an idea of the code that uses some index manipulation, but would like some help with checking the logic to see if I have this right. Here's the code I have so far.
void len_sort(char** words, int num_words)
{
int index=0;
int isSorted=0;
int string1_len;
int string2_len;
while(isSorted==0)
{
for(index=0;index<num_words;index++)
{
printf("%s\n", words[index]);
string1_len=strlen(words[index]);
if((index+1)==num_words)
string2_len=strlen(words[index]);
else
string2_len=strlen(words[index+1]);
if(string1_len<string2_len)
{
swap(words[index], words[index+1]);
}
}
isSorted=1;
for(index=0;index<num_words;index++)
{
string1_len=strlen(words[index]);
if(index+1==num_words)
string2_len=strlen(words[index]);
else
string2_len=strlen(words[index+1]);
if(string1_len>string2_len)
{
isSorted=0;
}
}
}
}
void swap(char* word1, char* word2)
{
char* temp;
word1=word2;
word2=temp;
}
I don't need to sort alphabetically, and I need to maintain the order of the words as they are in the array. for example: if I have something like
car
x
horse
a
my output should look like:
x
a
car
horse
keeping the fact that x is before a in the array true. Is there a better way to work with this sort for more efficiency??