Search code examples
csortingbubble-sort

Can anyone tell me the problem[s] in this bubble sort?


I have looked at several examples of this bubble sort but can't seem to find out what's wrong in mine, I'm weak with loops and such. I have to explain this to my class tomorrow so it'd be great if someone could help, thanks.

int main(){

int i,n,j,temp;
int a[] = {5,4,3,2,1};
n    = 5;

for(i=0;i<n;i++){
    for(j = 0;j<n-i-1;j++){
        if(a[j]>a[j+1]){            
            temp = a[j];                
            a[j] = a[j+1];
            a[j+1] = temp;
        }
    }
    printf("%d",a[i]);
}}

Solution

  • the problem is not in your bubble sort.you have miss placed printf remove it and add a loop like this after sorting loops:

        for (i = 0; i < 5; i++)
        {
            printf("%d ", a[i]);
        }