Bubble Sort using Recursion

I wrote this bubble sort algorithm after watching CPP-Recursion Sort Video. Even though this is the same code as shown in the video still, I am not getting the answer. Segmentation fault is coming.
Here, n is size of array, and j is initially 0 when the function in called.

void bubbleSort2(int arr[],int n,int j){
if(n==1)
    return ;
if(j==n-1)
    bubbleSort2(arr,n-1,0);
if(arr[j+1]<arr[j])
    swap(arr[j+1],arr[j]);
bubbleSort2(arr,n,j+1);
return; 
}
2 Likes

Hey Tanmay!
You are missing a return statement after the second if block where you compare j with n-1.

void bubbleSort2(int arr[],int n,int j){
if(n==1) {
     return ;
}

if(j==n-1){
     bubbleSort2(arr,n-1,0);
     // Line where the return statement was missing in your code
     return;
}

if(arr[j+1]<arr[j]) {
    
    swap(arr[j+1],arr[j]);
}
bubbleSort2(arr,n,j+1);
return;
}

The above code should work fine , see the issue was you were never returning from this recursion call and it was proceeding the code further making further recursive calls where out of bound exceptions were coming.
Hope it helps