Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I've tried impleamenting bubble sort on my own, the code breaks down when I provide random unsorted input, when I give sorted or reverse numbers

When I provide random unsorted input it breaks, when I give sorted or reverse sorted numbers it kinda works sometimes, I’ve checked for the algorithm I think it’s correct, swapping when if condition is not satisfied.

    #include <stdio.h>

int main()
{
    int N=10,max,a[N];
    printf("Enter the numbers:");
    for(int i=0;i<N;i++)
    {
        scanf("%d",&a[i]);
    }
    for(int i=0;i<N;i++)
    {
        printf("%d,",a[i]);
    }
    printf("\n");
    for(int i=0;i<N;i++)
    {
        for(int j=1;j<N;j++)
        {
            
            if (a[i]>a[i+j])
            {
                int temp=0;
                temp=a[i+j];
                a[i+j]=a[i];
                a[i]=temp;
            }
        }
    }
    for(int i=0;i<N;i++)
    {
        printf("%d,",a[i]);
    }
    return 0;
}

OUTPUT

Enter the numbers:78
96
78
5
69
3
7
6
9
2
78,96,78,5,69,3,7,6,9,2,
2,-1847346713,3,5,0,6,7,9,69,78,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The array a has N elements. The indexes i, and j can have a maximum value of N-1. Thus, when you access the array at i+j, you effectively access memory beyond the bounds of the array. Maybe change the condition in the inner for loop to for(int j=1;j+i<N;j++)

Also, a stylistic improvement may be to use size_t instead of int type variables as indices.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading