[英]why the swap part is executing again after the function hit return statement
the code is working fine till end and i am getting a sorted array, but after sorting it is again executing swap part code, but the issue is getting solved by adding else to the swap method.代码工作正常,直到结束,我得到一个排序数组,但排序后再次执行交换部分代码,但问题通过添加 else 到交换方法得到解决。
if(i==0){
return;
}
if(j<=i){
if(arr[j]>arr[max]){
max=j; //finding the max element in array
}
SS(arr,i,j+1,max);
}
int temp = arr[i];
arr[i] = arr[max]; //swapping the max element.
arr[max] = temp;
SS(arr, i - 1, 0, 0);
}
} }
This is working:这是有效的:
if(i==0){
return;
}
if(j<=i){
if(arr[j]>arr[max]){
max=j;
}
SS(arr,i,j+1,max);
i++;
}
else{
int temp = arr[i];
arr[i] = arr[max];
arr[max] = temp;
SS(arr, i - 1, 0, 0);
}
}
} }
what are the differences?有什么区别?
Well, without going deep into the algorithm, you have additional i++;
好吧,不用深入算法,你还有额外的
i++;
in the second if
branch in the second example.在第二个示例中的第二个
if
分支中。
Moreover in the first example the swap will happen even if the j<=i
condition is met because you did not add return
- it will not happen in the second example.此外,在第一个示例中,即使满足
j<=i
条件,交换也会发生,因为您没有添加return
- 在第二个示例中不会发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.