I have created a program that seeks input from the users about a 5 digit number (char datatype used) and it bubble sorts it out based upon the ascending or descending order, depending upon the parameter set in if statement.
CASE 1 : if (a[j] < a[j+1])
CASE 2 : if (a[j] > a[j+1])
Here's my code below :
int main()
{
char a[6];
int i, temp;
int j = 0;
printf("Enter a 5 digit number\n");
scanf("%s", a);
printf("You entered : %s\n", a);
for ( i = 0 ; i < 5 ; i++ )
{
for ( j = 0 ; j < 6 - 1 - i ; ++j )
{
if ( a[j] > a[j+1] )
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf("Bubble Sorted number : %s\n", a);
return 0;
}
This inner for loop
for ( j = 0 ; j < 6 - 1 - i ; ++j )
{
if ( a[j] > a[j+1] )
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
can overwrite the terminating zero character '\0'
of the string stored in the array a
.
When in the outer loop the variable i
is equal to 0
then you have actually the following inner loop
for ( j = 0 ; j < 5 ; ++j )
{
if ( a[j] > a[j+1] )
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
In this case when j
in the loop will be equal to 4
then the expression a[j+1]
that is the same as a[5]
will yield the terminating zero character that will be swapped with the character stored in the array element a[4]
.
Rewrite the inner loop like
for ( j = 1 ; j < 6 - 1 - i ; ++j )
{
if ( a[j-1] > a[j] )
{
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}