Recursive bubble sort in C is the sorting algorithm used to arrange a list in a particular form that can be ascending or descending in numerical or lexicographical order. It is among the most-used algorithms in C that include the likes of merge sort and selection sort.
Bubble sort is the simplest sorting algorithm. It is named so because the smaller or larger elements, depending on whether the order is descending or ascending, is “bubbled” to the top of the list.
Recursive Bubble Sort in C
There isn’t much difference between bubble sort and recursive bubble sort. The basics are the same, only the implementation differs. The latter is faster than the former and thus, is preferred more. Let’s start with understanding the basics of bubble sort using recursion.
To understand the recursive bubble sort in C better, we are here to explain an example. Before diving into the code, let’s first understand the algorithm that we will be using here.
Algorithm
STEP 1: If the array size is 1, then return.
STEP 2: Do One Pass of normal Bubble Sort on the given array. This will fix the last element of the current subarray.
STEP 3: Use Recursion for all elements except the last of the current subarray.
Example of Bubble Sort in C Using Recursion
Here is the program which shows how to implement the bubble sort in C using recursion:
#include<stdio.h>
void BubbleSortRecursion(int a[],int num);
main()
{
int i,j,num,temp;
printf("Enter number of elements\n");
scanf("%d",&num);
int a[num];
printf("Enter numbers\n");
for(i=0;i<num;i++)
{
scanf("%d",&a[i]);
}
BubbleSortRecursion(a,num);
printf("Given numbers in Ascending order \n");
for(i=0;i<num;i++)
{
printf("%d\n",a[i]);
}
}
void BubbleSortRecursion(int a[],int num)
{
int i,j,temp;
i=num;
if(i>0)
{
for(j=0;j<num-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
BubbleSortRecursion(a,num-1);
}
else
{
return;
}
}
Conclusion
That sums up this demonstration of implementing a recursive bubble sort in C. Please note that this is not a universal way of implementing bubble sort using recursion in C.
You can, therefore, write code that does the same but is different from the one mentioned above. Do let us know if you do so via the comments section below. All the best!
Comentários