【发布时间】:2016-12-09 13:37:09
【问题描述】:
我创建了一个冒泡排序程序。它最终陷入无限循环。 我在一些地方包含了 cmets,以便代码易于理解。 欢迎任何关于如何使代码更小的建议。
我在调试程序时发现了这个——
当stdin为“ccbbaa”时,经过一些递归,最终input(aabbcc)和temp(aabbcc)相同,然后strcmp()的条件执行后,'temp'的值变成了“baabcc” .
发生这种情况的任何原因? — 这就是无限循环的原因。
字符数组的末尾是否有“\0”(将输入复制到 temp 时)?
我通过使用 for 循环而不是 strcmp() 解决了这个问题。调查为什么 strcmp() 目前不起作用。
更新的代码可用 - http://ideone.com/4Bdblh(已解决)
错误代码
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
void sort(char* input)
{
const int length = strlen(input);
int j = length -1;
char temp[length];
for(int i=0; i<length; i++)
{
temp[i]= *(input+i);
}
while(j)
{
if((int)*(input+1) < (int)*(input))
{
char temp1;
temp1 = *(input);
*input = *(input + 1);
*(input + 1) = temp1;
}
input++;
j--;
}
input = input - length +1;
while(strcmp(temp,input))
{
sort(input);
}
}
int main()
{
char* input = malloc(sizeof(char)*1000);
scanf("%[^\n]%*c",input);
sort(input);
printf("%s",input);
return 0;
}
【问题讨论】:
-
谢谢,正在阅读。会记住以后的帖子。
-
你太复杂了......再次观看 CS50 的关于冒泡排序伪代码的视频,并尝试先使用简单的 char 数组来完成。没有指针算术或递归等。当您最终成功使其与数组和迭代一起使用时......然后您尝试递归,指针算术等
-
@PrakharSharma,我建议你暂时忘记
const。它并不完全是你认为的意思,除非你很好地理解它,否则它对你没有帮助。我还建议您采纳 yLaguardia 的建议来简化。你让这变得比它需要的复杂得多,这让你感到困惑。您不需要递归或指针算术,甚至不需要strlen()或strcmp()。虽然它可能不会伤害你,但你也不需要malloc()。
标签: c bubble-sort