-4

After compiling there are no outputs. cant seem to understand the issue. Also there are no errors while compiling .

#include<stdio.h>
void main(void)
{
    int a[] = {5,4,3,2,1};
    int i,j,min,b[5];
    min = a[0];
    for(i=0;i<sizeof(a);i++)
    {
        if(a[i]<min)
        {
            j = a[i];
            a[i] = min;
            min = j;
        }
        b[i] = min;
    }
    for(i=0;i<sizeof(b);i++)
    {
        printf("%d,",b[i]);
    }
}
  • 3
    Hint: sizeof(b) is not 5. – gnasher729 Oct 21 '17 at 15:19
  • 3
    Your sorting algorithm is bogus - that's how a typical bubble looks like. Have a look at [wikipedia](https://en.wikipedia.org/wiki/Bubble_sort). `sizeof(a)` gives the sizeof array `a` in *bytes*. In order to get the num of elements in `a`, you need to divide it by `sizeof a[0]`. Same applies to `sizeof(b)`. – P.P Oct 21 '17 at 15:19
  • `void main` is wrong. `main` should return `int`. – melpomene Oct 21 '17 at 15:20
  • ooo yes i got it now . thanks guys – P.L.Siriwardana Oct 21 '17 at 15:24
  • You need to learn how to debug. For instance, change the print statement to `printf("b[%d]\n: %d,",i, b[i])` to see what's going on. – klutt Oct 21 '17 at 15:26

1 Answers1

1

Change this:

sizeof(a)

to this:

sizeof(a)/sizeof(a[0])

since sizeof operator gives the size of the array a in bytes, and not the number of elements that you desire. So you divide by the size of an element of the array in bytes (all the elements of an array have the same size), which gives you the number of elements.

Same for sizeof(b).


Your algorithm doesn't seem quite correct. I suggest you take a look at the pseudocode of Bubble sort.


PS: What should main() return in C and C++? An int.

gsamaras
  • 66,800
  • 33
  • 152
  • 256