我当前正在从文件中读取单词列表,并尝试逐行排序。我可以把每一行都读进去,然后把单词打印出来,但我似乎无法单独对每一行进行排序。第一行已排序,但第二行未排序。有人看到我哪里错了吗?谢谢
int fd;
int n_char = 0;
int charCount = 0, wordCount = 0, lineCount = 0;
int wordsPerLine[100];
char buffer;
char words[6][9];
fd = open(inputfile, O_RDONLY);
if (fd == -1) {
exit(1);
}
wordsPerLine[0] = 0;
/* use the read system call to obtain 10 characters from fd */
while( (n_char = read(fd, &buffer, sizeof(char))) != 0) {
if (buffer == 'n' || buffer == ' ') {
words[wordCount][charCount] = ' ';
charCount = 0;
wordCount++;
wordsPerLine[lineCount] += 1;
if (buffer == 'n') {
lineCount++;
wordsPerLine[lineCount] = 0;
}
} else {
words[wordCount][charCount++] = buffer;
}
}
printf("Num Words: %d --- Num Lines: %dn", wordCount, lineCount);
char tmp[9];
int m, n;
int i, x, totalCount = 0;
for (i = 0; i < lineCount; i++) {
for (x = 0; x < wordsPerLine[i]; x++) {
/* iterate through each word 'm' in line 'i' */
for(m = 0; m < wordsPerLine[i]; m++) {
for(n = 0; n < wordsPerLine[i]; n++) {
if(strcmp(words[n-1], words[n])>0) {
strcpy(tmp, words[n-1]);
strcpy(words[n-1], words[n]);
strcpy(words[n], tmp);
}
}
} /* end sorting */
}
}
printf("Sorted:n");
totalCount = 0;
for(i = 0; i < lineCount; i++) {
printf("Line %d (%d words)n", i + 1, wordsPerLine[i]);
for(x = 0; x < wordsPerLine[i]; x++) {
printf("%sn", words[totalCount++]);
}
}
我的示例输入文件是:
great day out
foo bar food
让我们从小部分开始。。。
要查看问题是否在阅读中,请评论阅读部分并尝试添加:
char words[][9] = {"great", "day", "out", "foo", "bar", "food"};
并将计数器设置为使用此输入时的值。。。
您的循环正在访问一些超出范围的数据。。。我建议你先用一个数字数组来尝试你的排序代码,看看它是否正确排序。。。
#include<stdio.h>
#define N 6
int main()
{
char words[][9] = {"great", "day", "out", "foo", "bar", "food"};
int numbers[] = {20, 10, 50, 5, 30, -50};
int i, j, temp;
for(i = 0; i < N - 1; i++)
for(j = 0; j < N - 1; j++)
if(numbers[j] > numbers[j + 1])
{
temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
for(i = 0; i < N; i++)
{
printf("%dn", numbers[i]);
//printf("%sn", words[i]);
}
}
还请注意,这是冒泡排序的效率最低的实现(但与您提供的相同(,您可以通过添加一个变量来改进它,以在内部循环中检查例如发生的一些更改(这意味着它已经排序,您可以停止排序(。。。
此外,在外循环的每次迭代后,一个元素将被放置在其最终位置(尝试找出哪一个(,这意味着你不需要在下一次迭代中考虑这个元素,所以在外循环中的每次迭代之后,内循环中比较的元素数量可以减少1…
你可以在这里找到更多关于冒泡排序的信息
/* iterate through each line */
for (i = 0; i < lineCount; i++) {
/* iterate through each word 'm' in line 'i' */
for(m = 0; m < wordsPerLine[i]; m++) {
for(n = m+1; n < wordsPerLine[i]; n++) {
if(strcmp(words[n + totalCount], words[m + totalCount]) < 0) {
strcpy(tmp, words[m + totalCount]);
strcpy(words[m + totalCount], words[n + totalCount]);
strcpy(words[n + totalCount], tmp);
}
}
} /* end sorting */
totalCount += wordsPerLine[i];
}
我只需要保持每行每个单词的运行计数,这样我就知道应该从哪行开始与进行比较