Search code examples
cbubble-sort

breaking the bubble sort loop


After I can put a float in an array. I decided to do a bubble sort. And show every result when swap is happend

#include <stdio.h>

void print_array(float *number, int m){
    int i;
    for (i=0;i<m;i++){
        printf("%.2f ",number[i]);
    }
}
void swap(float *a, float *b)
{
    float temp = *a;
    *a = *b;
    *b = temp;
}
int main()
{
    unsigned int i,j,m;
    int flag = 0;
    printf("Input Size of Array : ");
    scanf("%d",&m);
    float number[m];
    for(i=0;i<m;i++){
        printf("Number %d : ",i+1);
        scanf("%f",&number[i]);
    }
    printf("\nBefore Sort => ");
    for(i=0;i<m;i++){
        printf("%.2f ",number[i]);
    }
    printf("\n\n");
    for(i=0;i<m;i++)
    {
        for(j=0;j<m-i-1;j++)
        {
            if(number[j] < number[j+1])
            {
                swap(&number[j],&number[j+1]);
                flag = 1;
            }
        }
        if(flag==0)
        {
            break;
        }
        printf("Sort # %d => ",i+1);
        print_array(number,m);
        printf("\n");
    }
    printf("\n--- Sort End ---");
}

I test it and found out that flag==00 didn't stop the loop. even if there is no more swap in the array.

How can I break the loop after it finish sorting?


Solution

  • Initiate value of flag in first loop.

    int flag;
    for(i=0; i<m; i++)
    {
        flag = 0;
        for(j=0; j<m-i-1; j++)
        {
            if(number[j] < number[j+1])
            {
                swap(&number[j],&number[j+1]);
                flag = 1;
            }
        }
        if(flag==0)
        {
            break;
        }
        printf("Sort # %d => ",i+1);
        print_array(number,m);
        printf("\n");
    }
    
    

    For every iteration, you want to stop if there's no swap operation.

    So before running the loop to do swap, you've to initiate the flag value.