Xael Yvette
Xael Yvette

Reputation: 77

Bubble Sort in C with zero

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

Answers (3)

kapil
kapil

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

redux
redux

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

user5152421
user5152421

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

Related Questions