Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make recursive bubble sort algorithm

I’m trying to change the implementation of bubbleSort below to be recursive.

void swap(int *x, int *y)
{
    int t = *x;
    *x = *y;
    *y = t;
}
  
void bubbleSort(int arr[], int n)
{
   for (int i = 0; i < n-1; i++)      
       for (int j = 0; j < n-i-1; j++) 
           if (arr[j] > arr[j+1])
              swap(&arr[j], &arr[j+1]);
}

How I can make the bubbleSort function recursive?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Possibly you need to change the implementation a little bit. Maybe the following will help:

void swap(int *x, int *y) {
    int t = *x;
    *x = *y;
    *y = t;
}

void bubbleSort(int arr[], int n) {
    if (n == 1) return;
        
    for (int i=0; i<n-1; i++)
        if (arr[i] > arr[i+1])
            swap(&arr[i], &arr[i+1]);
            
    bubbleSort(arr, n-1);
}

int main(void) {

    const int N = 7;
    int a[N] { 10, 15, 60, 40, 90, 50, 5 };

    for( int i = 0; i < N; i++) std::cout << a[i] << ',';
    std::cout << std::endl;

    bubbleSort(a, N);

    for( int i = 0; i < N; i++) std::cout << a[i] << ',';
    std::cout << std::endl;

}

The output of this program is:

10,15,60,40,90,50,5
5,10,15,40,50,60,90

(Demo)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading