1

I need to sort a given 2d array (char crossword[40][20]) by lines with lexicographical sort.
the crossword[40][20] contains:

TYPE
GUITARIST
VAIN
ROME
MARRIAGE
NOODLE
ANT
IN
PETROL
CUT
LIE
ATOM
MOUTH
ENVELOPE
IN
AT
AGE
ART
INTERIOR
AT
ROBBERY
AT
AIR
STIR
NO
IT
SMILE
NIGHT
ACE
MANDATORY
TO
NY
DO
OZONE
ON
UNDERWATER
NOUN

so crossword[0][columns]=TYPE, crossword[1][columns]=GUITARIST etc.
and must be converted to lexicographical order like that:

ACE  
ANT  
...  
...  
...  
VAIN

Of course i know how to bubblesort a 1d array but what happens with 2d like the above?
I want only the lines so the letters of the words stay as they are. I would appreciate if the code contains the strcmp.

Konstantinos
  • 943
  • 1
  • 9
  • 20
  • 1
    [I suggest you check out the answers to this question](http://stackoverflow.com/q/1787996/1679849) – r3mainer Dec 03 '14 at 00:36
  • @Konstantinos, as I currently don't have a C compiler at hand I don't want to post solutions as I can't test them, if you get stuck tell me where and I will try and update my answer to reflect it. – Emz Dec 03 '14 at 00:43

1 Answers1

0

int strcmp ( const char * str1, const char * str2 );

returns a negative value for str1 < str2, a positive value for str1 > str2 and a zero value for str1 = str2.

That sounds useful. Remember that words in C are just arrays of char. So we can iterate over the words doing strcmp (...) for for the indexes.

Now we are almost on the same level of sorting integers in a one-dimensional array.

We also need a temp variable (just as with a standard bubble sort for integers). Remember to use strcpy() when swapping objects around.

So our code will look something along the lines of

#define MAX 40

int i, j;

char temp[20];
for (i = 0; i < MAX-1; ++i)
{
    for (j = i+1; j < MAX; ++j)
    {
        if (strcmp (words[i], words[j]) > 0)
        {
            strcpy (temp, words[i]);
            strcpy (words[i], words[j]);
            strcpy (words[j], temp);
        }
    }
}

Note:- Not yet tested by me.

MathMan
  • 103
  • 4
Emz
  • 1,280
  • 1
  • 14
  • 29
  • Two things, if they are equal to each other, you don't need to move them. I think you also mean `i != j`. Else you will only compare the word to itself. – Emz Dec 03 '14 at 00:50
  • What was the error? I could add it to the answer. You also don't need the `i != j` as `j` will always be one value above. – Emz Dec 03 '14 at 01:00