简体   繁体   English

用strcmp排序并冒泡在C中二维数组

[英]Sort with strcmp and bubblesort a 2d array in C

I need to sort a given 2d array (char crossword[40][20]) by lines with lexicographical sort. 我需要按字典顺序对给定的二维数组(char crossword [40] [20])进行排序。
the crossword[40][20] contains: 填字游戏[40] [20]包含:

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. 因此,填字游戏[0] [栏] =类型,填字游戏[1] [栏] = GUITARIST等。
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? 当然我知道如何对1d数组进行冒泡排序,但是像上面的2d会发生什么?
I want only the lines so the letters of the words stay as they are. 我只需要这些行,以便单词的字母保持原样。 I would appreciate if the code contains the strcmp. 如果代码包含strcmp,我将不胜感激。

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 . 对于str1 < str2返回负值,对于str1 > str2 str1 = str2正值,对于str1 = str2零。

That sounds useful. 听起来很有用。 Remember that words in C are just arrays of char. 请记住,C语言中的单词只是char的数组。 So we can iterate over the words doing strcmp (...) for for the indexes. 因此,我们可以遍历为索引执行strcmp (...)的单词。

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). 我们还需要一个temp变量(就像对整数进行标准冒泡排序一样)。 Remember to use strcpy() when swapping objects around. 在交换对象时,请记住使用strcpy()

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. 注意:-尚未由我测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM