C代码出现Time Limit Exceeded错误,改用goto后仍异常如何解决?
问题分析:死循环导致超时/无响应的根源
看起来你把冒泡排序改写成goto版本时踩了个经典的坑——死循环!导致在线IDE超时、本地控制台无响应的原因很明确:
原代码的外层for循环中,每次迭代后n会自动执行n--,直到n>1不成立时退出循环。但你的goto版本里,当内层循环完成跳转到Lelse后,直接回到了Lcond判断,完全没有处理n的递减操作!这就导致n永远保持初始的length值,n<=1的退出条件永远不满足,程序一直在外层循环里无限打转。
修正后的代码
只需要在Lelse标签处添加n--;,让外层循环的控制变量和原代码一样递减,就能解决问题。修正后的完整代码如下:
#include <stdio.h> void sort(int skip,int *A,int length){ int n=length; int i,temp,temp2; Lcond: if(n<=1) goto Lend; Lbody: i=0; Lcond_: if(skip!=0) goto Lelse; temp=n-1; if(i>=temp) goto Lelse; Lbody_: temp2=i+1; if(A[i]>A[temp2]) goto Lbody__; i++; goto Lcond_; Lbody__: A[i]=A[i]^A[temp2]; A[temp2]=A[temp2]^A[i]; A[i]=A[i]^A[temp2]; i++; goto Lcond_; Lelse: n--; // 关键修正:添加n的递减操作,匹配原代码的外层循环逻辑 goto Lcond; Lend: return; } int main(){ int skip=0; int A[5]={3,5,1,4,2}; int length=5; sort(skip,A,length); for (int i=0;i<5;i++){ printf("%d\t",A[i]); } }
验证结果
运行修正后的代码,会正确输出排序后的数组:1 2 3 4 5,不会再出现超时或无响应的问题。
内容的提问来源于stack exchange,提问作者donpwner
相关产品推荐
相关产品推荐

