user3314399
user3314399

Reputation: 325

C Bubble Sort algorithm

I have the following code which sorts the strings using bubble sort logic. The part that I am confused about is the for loop which Im not sure why i is set to one and why J is iterated until it is less than n-j:

#include <stdio.h>
#include <string.h>
void main()
{
    char name[25][50],temp[25];
    int n, i, j;
    printf("\n\nSorts the strings of an array using bubble sort :\n");
    printf("-----------------------------------------------------\n");
    printf("Input number of strings :");
    scanf("%d",&n);
    printf("Input string %d :\n",n);
    for(i=0; i<=n; i++)
    {
        fgets(name[i], sizeof name, stdin);
    }

    /*Logic Bubble Sort*/
    for(i=1; i<=n; i++)
    {
        for(j=0; j<=n-i; j++)
        {
           if (strcmp(name[j],name[j+1])>0)
           {
               strcpy(temp,name[j]);
               strcpy(name[j],name[j+1]);
               strcpy(name[j+1],temp);
           }
        }
    }
    printf("The strings appears after sorting :\n");
    for(i=0;i<=n;i++)
        printf("%s\n",name[i]);
}

Upvotes: 0

Views: 165

Answers (1)

Rishikesh Raje
Rishikesh Raje

Reputation: 8614

There are a few subtle things wrong with this code

  1. You are running the for loop one more than necessary.

    for(i=0;i<=n;i++)
    {
        fgets(name[i], sizeof name, stdin);
    }
    

The reason that is the line above scanf("%d",&n);

Here the end of line remains in the input stream and is being added to name[0]. You should change it to scanf("%d ",&n);

This will consume the end of line in the same statement. Also the for loop should now run from for(i=0;i< n;i++).

Additionally, the fgets function receives a size of name which is too large. It should receive a size of name[0] i.e. fgets(name[i], sizeof name[0], stdin);

  1. Now, your strings are being stored from name[0] to name[n-1] and the rest of your sort algorithm can be fixed.

    for(i=0;i< n;i++){
        for(j=0;j< n-i;j++)
        {
            if(strcmp(name[j],name[j+1])>0)
            {
                strcpy(temp,name[j]);
                strcpy(name[j],name[j+1]);
                strcpy(name[j+1],temp);
            }
        }
    }
    printf("The strings appears after sorting :\n");
    for(i=0;i< n;i++)
        printf("%s",name[i]);
    

The reason for the inner for loop going from 0 to n-i is that at the end of 1 outer loop the largest element is in names[n-1]

After 2 outer loops, 2 elements are sorted [n-2] and [n-1]. So there is no need to check these elements.

And so on.

Upvotes: 3

Related Questions