Question

I made this bubble sort algorithm in C. Its working well in DM, but when executed in gcc, gives me incorrect output.

#include <stdio.h>

int i,j;

void BubbleSort(int*a, int n) //to sort the numbers
{
    int temp;
    for(i=0; i<n;i++)
        for(j=n; j>i;j--)
            if (a[j]<a[j-1])
                {
                    temp=a[j];
                    a[j]=a[j-1];
                    a[j-1]=temp;
                }
}

void Display(int * a, int n) //to display
{
    printf("\nThe sorted numbers are:\n");
    for(i=0;i<n;i++)
        {
            printf("%d, ",a[i]);
        }
}

int main()
{
    int a[50],n,choice;
    printf("\nEnter no. of elements to sort: (max. 50) ");
    scanf("%d",&n);
    printf("\nEnter the numbers : ");

    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    BubbleSort(a,n);
    Display(a,n);

    return 0;

} //End of main

Input:

5
2 1 5 3 4

DM Output:

1, 2, 3, 4, 5,

GCC Output:

1, 2, 3, 5, 4,

How and why is this happening?

Was it helpful?

Solution

The fact that this works at all is suspect. You're overstepping the original array on this line:

if (a[j]<a[j-1])  // sketchy when j==n

You're comparing a value that you haven't initialized so the value at a[n] is whatever is there upon initialization.

This line:

for(j=n; j>i;j--)

should be:

for(j=n-1; j>i;j--)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top