Reputation: 77
So, I'm trying bubble sort for the first time in C and my code works except for the fact that if I enter 0 as an input the sorting makes everything else 0. I can't figure out what's wrong with my code. Thank you.
/* Double-Click To Select Code */
#include<stdio.h>
void main()
{
int w,f,temp,j;
float arr[25];
printf("Enter the number of elements in the Array: ");
scanf("%d",&f);
printf("\nEnter the elements:\n\n");
for(w=0 ; w<f ; w++)
{
printf(" Array[%d] = ",w);
scanf("%f",&arr[w]);
}
for(w=0 ; w<f ; w++)
{
for(j=0 ; j<f-w-1 ; j++)
{
if(arr[j]>arr[j+1]) //Swapping Condition is Checked
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf("\nThe Sorted Array is:\n\n");
for(w=0 ; w<f ; w++)
{
printf(" %4f",arr[w]);
}
}
if I input say, 1.000 0.333 0
the output would be: 0.000 0.000 1.000
Upvotes: 2
Views: 252
Reputation: 624
the temp variable being of int type truncates the float value. change it to float.In your output 0.000 0.000 1.000 the first or the second zero was 0.33 truncated to zero and the third value is at is
Upvotes: 0
Reputation: 1167
Assuming you are trying to sort floats, you need temp to be a float:
int w,f,j;
float arr[25];
float temp;
Upvotes: 0
Reputation:
I tested. Just change the type of temp to float. This is working;
#include<stdio.h>
void main()
{
int w,f,j;
float arr[25],temp;
printf("Enter the number of elements in the Array: ");
scanf("%d",&f);
printf("\nEnter the elements:\n\n");
for(w=0 ; w<f ; w++)
{
printf(" Array[%d] = ",w);
scanf("%f",&arr[w]);
}
for(w=0 ; w<f ; w++)
{
for(j=0 ; j<f-w-1 ; j++)
{
if(arr[j]>arr[j+1]) //Swapping Condition is Checked
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf("\nThe Sorted Array is:\n\n");
for(w=0 ; w<f ; w++)
{
printf(" %4f",arr[w]);
}
system("pause");
}
Upvotes: 1