Why we have used this statement *return bubble(a,n-1,0);* and what is the use of it

#include
using namespace std;
void bubble(int*a,int n,int bp){
if(n==1){
return;
}
if(bp==n-1){
return bubble(a,n-1,0);
}

    if(a[bp]>a[bp+1]){
        swap(a[bp],a[bp+1]);
    }

bubble(a,n,bp+1);

}

int main() {
int n; cin>>n;
int a[n]={1,44,12,23,5};
bubble(a,n,0);
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
}

@himanshuep32 Logic is same as the iterative bubble sort. You have used that statement in the base case which will execute if(bp==n-1) ie. when the pointer j moves to the last element in the window. Recall that in normal bubble sort, you use two loop i and j. For each i , you iterate over j and swap adjacent elements. After first iteration of i completes, the largest element in the array settles at the last position. At the 2nd iteration of i, the 2nd largest element settles at the 2nd last position and so on. You can see that the array gets sorted gradually from the end. This is why return bubble(a,n-1,0); is used. This just means that element after n-1th index is already sorted so call bubble sort for the reamining part which is from position 0 to n-1.

Hope this helps :slightly_smiling_face:

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.