I am working on a coding problem when I have to sort an array of words (pointers to strings) by word length. I have an idea for code that uses some manipulation of indexes, but would like to help with checking the logic to make sure I'm right. Here is the code I have.
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 do not need to sort in alphabetical order, and I need to maintain the order of words as they are in the array. for example: if I have something like
car
x
horse
a
my output should look like this:
x
a
car
horse
preserving the fact that x to a in the array is true. Is there a better way to work with this type for greater efficiency?
source
share