I am trying to make a recursive function to sort an array. The idea is to swap two elements whenever the one with smaller index is larger, because we want to sort into ascending order. The following is the program in C that I have written for this
void sort(int a[30], int n)
{
int m = 0,i,temp;
for(i = 0;i<n-1,m==0;i++)
{
printf("The array when i is %d is %d",i,a[0]);
for(i=1;i<n;i++)
printf(",%d",a[i]);
printf("\n");
if(a[i]>a[i+1])
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
m = 1;
}
}
if(m==0)
{
printf("The sorted array is %d",a[0]);
for(i=1;i<n;i++)
printf(",%d",a[i]);
}
else
sort(a,n);
}
int main()
{
int a[30],n;
printf("Enter the number of elements\n");
scanf("%d",&n);
if(n>30||n<1)
printf("The number of elements should be a natural number not exceeding 30");
else
{
int i;
for(i=0;i<n;i++)
{
printf("Enter element number %d\n",i+1);
scanf("%d",&a[i]);
}
sort(a,n);
}
return 0;
}
This program is not giving desired output, it runs into a very long loop (even for n=4), and then suddenly stops.
Can somebody please detect the problem??