I didn’t write the return statement in the j==n-1 if condition but however my code returns segmentation fault. I didn’t understand why it is necessary to use the return statement here and why it is giving segmentation fault even in that case…
my code link: https://ideone.com/D1V5Mp
Why is use of the return statement is necessay here
reason is if you did’nt return after function call then after the recursive call is executed for j=n-1
“if (ar[j] > ar[j + 1])” this statement will execute next and since j=n-1 then ar[j+1] which will be ar[n] will be accessed thus giving you segmentation fault for accessing undefined memory
so the correct code is :-
void bubble_re(int ar[], int j, int n)
{
if (n == 1)
return;
if (j == n - 1){
bubble_re(ar, 0, n - 1);
return ;
}
if (ar[j] > ar[j + 1])
swap(ar[j], ar[j + 1]);
bubble_re(ar, j + 1, n);
}
In case of any doubt feel free to ask
mark your doubt as resolved if you got the answer
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.