【问题标题】:Sorting lines of a 2D array in C在C中对二维数组的行进行排序
【发布时间】:2014-08-10 16:30:58
【问题描述】:

我正在尝试按字母顺序对二维数组中的每一行进行排序。 我正在从一个文件中读取,我可以做到这一点:

int n_char = 0;
int charCount = 0, wordCount = 0, lineCount = 0;
int wordsPerLine[100];

char buffer;
char words[50][75];

wordsPerLine[0] = 0;
while( (n_char = read(fileDescriptor, &buffer, sizeof(char))) != 0) {


        if (buffer == '\n' || buffer == ' ') {

            words[wordCount][charCount] = '\0';
            charCount = 0;
            wordCount++;
            wordsPerLine[lineCount] += 1;
            if (buffer == '\n') {
                lineCount++;
                wordsPerLine[lineCount] = 0;
            }

        } else {

            words[wordCount][charCount++] = buffer;


        }
    }

所有的单词和行都读得很好,但是现在我在对行进行排序时遇到了问题。我知道每行有多少个单词,也知道数组中有多少行,所以现在我正在对所有单词进行计数,并注意新行的第一个单词。我的问题是如何对所有行进行排序?

到目前为止,我只有这个:

int runningSize = 0;
for(i = 0; i < lineCount; i++) {
    printf("%d\n", runningSize);
    printf("\t%s\n", words[runningSize]);
    runningSize += wordsPerLine[i];
}

如果不清楚,这里有一个例子:

输入:

hello world
goodbye world
elephants are really cool

预期输出:

elephants are really cool
goodbye world
hello world

【问题讨论】:

  • 您的问题应该是:如何对多行字符串进行排序.... 2-你关心你的排序是否稳定?
  • 是的,你是对的——我的措辞肯定是错误的。而且它不一定要稳定,我只想要线条排序哈哈。
  • 好吧,这更清楚了,大卫有一个很好的解决方案给你:)

标签: c arrays sorting multidimensional-array


【解决方案1】:

为什么要重新发明轮子。您可以使用其中一种包含的排序算法来为您完成此操作。以下示例显示如何使用qsort 对字符串进行排序。它可以很容易地适应您的情况:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void sortstrarr(void *array, unsigned n);
static int cmpr(const void *a, const void *b);

int main(void) {
    char line[1024];
    char *line_array[1024];
    int i = 0;
    int j = 0;

    printf ("Enter one string per line (ctrl+d when done)\n");

    while(fgets(line, 1024, stdin)) {

        if (i < 1024)
            line_array[i++] = strdup(line);
        else
            break;
    }

    printf ("\npassing strings to sortstrarr (using qsort)\n\n");

    sortstrarr (line_array, i);

    while (j < i)
        printf ("%s", line_array[j++]);

    return 0;
}

static int cmpr (const void *a, const void *b) {
    return strcmp(*(char **)a, *(char **)b);
}

void sortstrarr (void *array, unsigned n) {
    qsort (array, n, sizeof(char *), cmpr);
}

输出

Enter one string per line (ctrl+d when done)
this is my string
alother one
maybe one more
been there
done that

passing strings to sortstrarr (using qsort)

alother one
been there
done that
maybe one more
this is my string

【讨论】:

  • 你需要注意这个排序是不稳定的。我想知道你怎样才能让它稳定且高效
  • 怎么@AK_?当您说不稳定时,您的意思是它崩溃或排序顺序混乱?
  • 根本不是大卫,我的意思是你使用的排序算法(qsort)不是稳定 - 我认为这里所说的例子很清楚:en.wikipedia.org/wiki/Sorting_algorithm#Stability 编辑:提问者说它不需要稳定所以你很好:)
  • 哦!对不起,我当时选择了那个,你可以使用任何你喜欢的排序,bubblesort,heapsort 等等,我刚刚在我的一个文件中有一个 qsort 示例,可以使用了。
  • 没关系,我认为 qsort 在这种情况下做得很好(例如比冒泡排序更有效)——还有一个问题:你为什么将strcmp 声明为静态?你能解释一下吗?
猜你喜欢
  • 2019-05-17
  • 2015-01-30
  • 2012-12-15
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
  • 2017-12-04
相关资源
最近更新 更多