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??
In the condition of the if statement
for(i = 0;i<n-1,m==0;i++)
there is used the comma operator. Its value is the value of the right hand operand that is of m==0.
I think you mean
int m = 1;
for (i = 0; m != 0 && i<n-1; i++ )
{
m = 0;
//...
That is if in the inner loop there was not swapping elements of the array that means that the array is already sorted then m will be equal to 0 and the outer loop will stop its iterations.
Also withing the inner loop you have to use another variable for the index not i
.
Here is a demonstrative program that shows how the function can be implemented based on the method bubble sort.
#include <stdio.h>
void bubble_sort( int a[], size_t n )
{
if ( !( n < 2 ) )
{
size_t last = 1;
for ( size_t i = last; i < n; i++ )
{
if ( a[i] < a[i-1] )
{
int tmp = a[i];
a[i] = a[i-1];
a[i-1] = tmp;
last = i;
}
}
bubble_sort( a, last );
}
}
int main(void)
{
int a[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
const size_t N = sizeof( a ) / sizeof( *a );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
bubble_sort( a, N );
for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );
return 0;
}
The program output is
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9