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

Viewed 39

When I provide random unsorted input it breaks, when I give sorted or reverse sorted numbers it kind of 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,
1 Answers

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.

Related