【发布时间】:2013-05-02 21:55:56
【问题描述】:
我必须使用冒泡排序技术按字典顺序对字符串进行排序,而不使用任何库函数。我编写了以下代码,在对字符串进行排序时效果很好。
但问题是,如果我给 n 作为输入(比如 n = 4),我只能输入 n-1 个字符串(只有 3 个字符串)。
这个问题可以通过从 0 到 n 运行 for 循环来解决,但这不是一个合乎逻辑的解决方案。
我在这里做错了什么?
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void swap(int indx[], int j)
{
int temp;
temp = indx[j];
indx[j] = indx[j+1];
indx[j+1] = temp;
}
void sort(char **str, int indx[], int n)
{
int i, j, k;
for(i=0; i<n; i++)
{
for(j=0; j<n-i-1; j++)
{
k = 0;
while(str[j][k] != '\0')
{
if((str[indx[j]][k]) > (str[indx[j+1]][k]))
{
swap(indx, j);
break;
}
else if((str[indx[j]][k]) < (str[indx[j+1]][k]))
break;
else
k++;
}
}
}
}
void display(char **str, int indx[], int n)
{
int i;
printf("Sorted strings : ");
for(i=0; i<n; i++)
printf("%s\n", str[indx[i]]);
}
int main(void)
{
char **str;
int n, i, j, *indx;
printf("Enter no. of strings : ");
scanf("%d", &n);
str = (char **) malloc (n * (sizeof(char *)));
indx = (int *) malloc (n * sizeof(int));
for(i=0; i<n; i++)
str[i] = (char *)malloc(10 * sizeof(char));
printf("Enter the strings : ");
for(i=0; i<n; i++)
{
gets(str[i]);
indx[i] = i;
}
sort(str, indx, n);
display(str, indx, n);
}
【问题讨论】:
-
我不明白... 1)为什么只能输入n-1个字符串?你不说是什么问题。 2) 为什么将循环从 0 运行到 n 是“不合逻辑的”?
-
注意:C 标准说函数
malloc()是在<stdlib.h>中声明的(不是<malloc.h>);它也根本不谈论任何名为<malloc.h>的标题。 -
@KScottPiel 要回答你的第一个问题,让我们举这个例子,如果我给“输入字符串数”4,那么我实际上只能输入 3 个字符串。要回答您的第二个问题,如果我们从 0 开始数组索引,我们通常会上升到 n-1。因此,如果我们从 0 到 n 遍历数组,我们实际上是在遍历一个额外的元素,据我所知,这不符合逻辑。
-
你不是从 0 到 n 遍历数组,而是从 0 到小于 n 的数组。
-
啊,找到问题了。
标签: c arrays string multidimensional-array bubble-sort