gpt4 book ai didi

c - 冒泡排序以无限循环结束

转载 作者:行者123 更新时间:2023-11-30 15:02:27 25 4
gpt4 key购买 nike

我创建了一个冒泡排序程序。它最终陷入无限循环。我在一些地方添加了注释,以便代码易于理解。欢迎任何有关如何缩小代码的建议。

我在调试程序时发现了这个 -

当标准输入为“ccbbaa”时,经过一些递归,最终输入(aabbcc)和temp(aabbcc)相同,然后执行strcmp()的条件后,“temp”的值更改为“baabcc” .

  1. 有什么原因可以解释为什么会发生这种情况吗? ——这就是无限循环的原因。

  2. 字符数组末尾是否有“\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;
}

最佳答案

使用数组和 for 循环回答 -

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<ctype.h>
#define MAX 1000

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];
}
int l=0;
while(j)
{

if(input[l+1] < input[l])
{
char temp1;
temp1 = input[l];
input[l] = input[l+1];
input[l+1] = temp1;
}
l++;
j--;
}
for(int k=0; k<length; k++)
{
if(temp[k]!=input[k])
{
sort(input);
}
}
}
int main()
{
char input[MAX];
scanf("%[^\n]%*c",input);
sort(input);
printf("%s",input);
return 0;
}

关于c - 冒泡排序以无限循环结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41061736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com