How to write a while loop which is identical to for loop in c

yaswanth reddy Source

I've encountered strange behaviour while writing bubble sort in c. The code i wrote using for loop is (which is working as i thought),

int arr[] = {-1,3333,1,3,4,2,3,4,5,6,7,4,11,12,332,1,-11};
    int i,j;
    int size = sizeof(arr)/sizeof(arr[0]);
    print_array(arr,size);
    for(i=0;i<size-1;i++)
        for(j=1;j<size-i;j++)
            if(arr[j]<arr[j-1])
                swap(&arr[j],&arr[j-1]);
    print_array(arr,size);

which gives me the output:

given array: -1,3333,1,3,4,2,3,4,5,6,7,4,11,12,332,1,-11

sorted array: -11,-1,1,1,2,3,3,4,4,4,5,6,7,11,12,332,3333

but when i rewrote the same bubble sort using while loops(not working as planned),

    int arr[] = {-1,3333,1,3,4,2,3,4,5,6,7,4,11,12,332,1,-11};
    int i=0,j=1;
    int size = sizeof(arr)/sizeof(arr[0]);
    print_array(arr,size);
    while(i<size-1)
    {
        while(j<size-i)
        {
            {
                if(arr[j]<arr[j-1])
                    swap(&arr[j],&arr[j-1]);
            }
            j++;
        }
        i++;
    }
    print_array(arr,size);

which gives output,

given array: -1,3333,1,3,4,2,3,4,5,6,7,4,11,12,332,1,-11

sorted array: -1,1,3,4,2,3,4,5,6,7,4,11,12,332,1,-11,3333

what am i missing ? (i am using gcc comiler in linux).

csorting

Answers

answered 5 days ago Rizwan #1

for(j=1;j<size-i;j++)

you forgot to include j=1; in your while loop implementation.

while loop should be like :

while(i<size-1)
{
    j=0; // set j=0 here
    while(j<size-i)
    {
        {
            if(arr[j]<arr[j-1])
                swap(&arr[j],&arr[j-1]);
        }
        j++;
    }
    i++;// OR you can set j=0 here also (any one place)
}

comments powered by Disqus