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?
>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)